Ninject to ASP.NET MVC 6 DI Translation

I am trying to get into the new ASP.NET MVC 6 stuff, but it is very difficult for me with their new DI system. I tried to find resources on the Internet, but everything that I find covers only an absolute minimum to use it.

I previously used Ninject , and I have several connections that work as follows:

 Bind<IDocumentStore>() .ToMethod(c => CreateDocumentStore()) .InSingletonScope(); private static IDocumentStore CreateDocumentStore() { // lots of initialization code, etc. return documentStore; } 

But so far, it’s hard for me to find a way to transfer this behavior to the new Microsoft DI system. All I can find are examples:

 services.AddTransient<IEmailSender, AuthMessageSender>(); services.AddTransient<ISmsSender, AuthMessageSender>(); 

and

 services.AddMvc(); 

Where everything seems to work completely with the standard constructor for the target service. Is there a way to create the behavior that I need in this new DI system?

I have seen

 services.Configure<TOptions>(options => {}); 

But I do not quite understand if this will do what I think about, or if it is reserved for a specific behavior.

+9
dependency-injection asp.net-mvc asp.net-core-mvc
Jul 29 '15 at 8:29
source share
2 answers

The AddTransient method has various overloads, one of which accepts a lambda expression:

 services.AddTransient<IDocumentStore>(s => CreateDocumentStore()); 

However, it looks like you are using the Ninject InSingletonScope() modifier, so this might be more appropriate:

 services.AddSingleton<IEmailSender>(s => CreateDocumentStore()); 

Additional note: there is some preliminary version of the documentation (of course, it is not completed and may be incorrect, but it may help)

+7
Jul 29 '15 at 8:39
source share

You can also continue to use Ninject by adding the Microsoft.Framework.DependencyInjection.Ninject project to the project, and then configure it with the following code:

 public IServiceProvider ConfigureServices(Microsoft.Framework.DependencyInjection.IServiceCollection services) { var kernel = CreateMyKernel(); kernel.Populate(services); // Wire up configured services and Ninject kernel with Microsoft tool return kernel.Get<IServiceProvider>(); } 
+3
Jul 29 '15 at 9:53 on
source share



All Articles