Asp.net core using Autofac
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.