Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translating Ninject to ASP.NET MVC 6 DI

I am trying to get into the new ASP.NET MVC 6 stuff, but I'm having a very hard time with their new DI system. I have tried to find resources online, but everything I find covers only the absolute most bare minimum to use it.

I was previously using Ninject, and I have several wire-ups that work like this:

Bind<IDocumentStore>()
    .ToMethod(c => CreateDocumentStore())
    .InSingletonScope();

private static IDocumentStore CreateDocumentStore() {
    // lots of initialization code, etc.
    return documentStore;
}

But so far I am having a difficult time finding out how to translate this kind of behaviour to Microsoft's new DI system. All I can find are examples like this:

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

and:

services.AddMvc();

Where everything seems to work entirely on the default constructor for the target service. Is there any way to produce the behaviour I am needing in this new DI system?

I've seen the

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

But I'm not really clear on whether that will do what I am thinking, or if it is reserved for specific behaviours.

like image 453
Ciel Avatar asked Jul 29 '15 08:07

Ciel


2 Answers

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

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

However it seems you are using the Ninject InSingletonScope() modifier so this may be more appropriate:

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

Additional note: There is some pre-release documentation available (of course, it's not complete and may be incorrect but may help)

like image 151
DavidG Avatar answered Nov 07 '22 22:11

DavidG


Also you could continue use Ninject by adding Microsoft.Framework.DependencyInjection.Ninject to your project and then configure it with 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>();
}
like image 36
STO Avatar answered Nov 07 '22 21:11

STO