Asp.net core's built-in service container is intended to provide the basic requirements of the framework on which most client applications are built.

Of course, developers can easily replace the default container with their preferred container. The ConfigureServices method usually returns void , but if its signature is changed to return IServiceProvider, a different container can be configured and returned.

There are many IOC containers to choose from in the development process. Here is an example of using the Autofac package.

1. Install Autofac in the project

Install-Package Autofac
Install-Package Autofac.Extensions.DependencyInjection

2. Configure the container in configureservices and return iserviceprovider

public class Startup
{
    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
      // Add Autofac
      var containerBuilder = new ContainerBuilder();
      containerBuilder.Populate(services);
      containerBuilder.RegisterModule<AutofacModule>();
      Startup.AutofacContainer = containerBuilder.Build();
      return new AutofacServiceProvider(Startup.AutofacContainer);
    }

    public static IContainer AutofacContainer { get; set; }
}

Note: the order of Populate method and RegisterModule is to register services in the aotofac container. During configuration, the same interface will be overwritten by the later registered services.

3. configure AutofacModule in Autofac

public class AutofacRepository : IRepository
{
    public string GetInfo()
    {
        return "autofac!";
    }
}

public class AutofacModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterType<AutofacRepository>().As<IRepository>();
    }
}

4. Use and test

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.Map("/autofac", autofacApp => {
        autofacApp.Run(async (context) => {
            var info = Startup.AutofacContainer.Resolve<IRepository>().GetInfo();
            await context.Response.WriteAsync(info);
        });
    });
}

Other people

At run time, Autofac will be used to resolve types and inject dependencies. Learn more about using Autofac And ASP.NET Core

All Comments

Leave a Reply Cancel Reply

Tips: Your email address will not be disclosed!

If you can't see clearly,please click to change...

Popular Posts

Collections