VivekDev
VivekDev

Reputation: 25389

DI Modules in ASP.NET Core built-in DI system

I have been using NInject for some time, and now I will be starting a project in Asp.net core. Seems NInject cannot be used with Asp.net Core. So now my question is does Asp.net core provide any di modules just as NInject or other di containers provide?

Upvotes: 3

Views: 7537

Answers (4)

Dario Griffo
Dario Griffo

Reputation: 4274

You can try ServiceCollection.Extensions.Modules from nuget here

Upvotes: 1

Ilya Chernomordik
Ilya Chernomordik

Reputation: 30205

Just to add to the other good answers, you can use e.g. SimpleInjector. It's a brilliant DI-container that supports .Net Core (and ASP.Net Core as well). See details of how to use it with .Net Core here.

Upvotes: 3

Tseng
Tseng

Reputation: 64150

ASP.NET Core doesn't provide any module support at all. It is designed to be a simple out-of-the-box container where 3rd parties IoC container can plug-in.

So there are no auto-registration, assembly scannings, decorators, interceptors or modules. If you want them, you need to use 3rd party frameworks (AutoFac, StructureMap etc.).

3rd party libraries do register using Registration methods, which are called like services.AddXxx() in ConfigureServices method.

public static class MyLibraryServiceCollectionExtensions
{
    public static IServiceCollection AddMyLibrary(this IServiceCollection services)
    {
        services.TryAddScoped<IMyService,MyService>();

        return services;
    }
}

It is preferred way to register libraries (cause it doesn't depend on any IoC container except for the built-in IServiceCollection, which 3rd party containers use too when plugged in ASP.NET Core), for stuff like "business logic library" there isn't really such a thing (where modules were useful before).

Upvotes: 13

Haitham Shaddad
Haitham Shaddad

Reputation: 4456

Asp.Net Core provides out of the box DI framework, it allows you to add an object for each resolve request, per Http Request or a singleton. All of this is done in the ConfigureServices method ex:

public void ConfigureServices(IServiceCollection services)
{
    //Your configuration

    // Add application services.
    services.AddTransient<IEmailSender, AuthMessageSender>();
    services.AddTransient<ISmsSender, AuthMessageSender>();
}

You can read more about it here

https://docs.asp.net/en/latest/fundamentals/dependency-injection.html

Upvotes: -6

Related Questions