.Net Core itself provides a simple framework for DI, DI to meet our basic needs. It depends on the following components, taken from the need to pull down Nuget package.
Microsoft.Extensions.DependencyInjection.Abstractions
Of which there are two more important objects, ServiceCollection and ServiceProvider. The former is DI container, each representative of the set of service instances, provides some basic injection method, the following example
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddTransient <IBookDAL2, MemoryBookDAL2> () ;
services.AddScoped <IBookDAL3, MemoryBookDAL3> ();
The latter is responsible for maintaining Service instances, including creation and destruction. This object also provides extension points integrate third-party components. It can be obtained by a method BuildServiceProvider IServiceCollection extension interface.
This is the .Net Core own DI framework of some basic, very simple to use. In the daily development process, we could use some more professional DI components, we are here to try to use Autofac integrated look.
First Nuget package, do not pull the wrong.
Autofac.Extensions.DependencyInjection
Integrated follows, ConfigureServices method needs to return the IServiceProvider . Special attention under builder.Populate (services); Explanatory notes
public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddMvc(cfg => { var filter = ApplicationContainer.Resolve<DefaultExceptionFilterAttribute>(); //var filter = services.BuildServiceProvider().GetService<DefaultExceptionFilterAttribute>(); if (filter != null) cfg.Filters.Add(filter); }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2); var serviceProvider = AutoFacRegister(services); return serviceProvider; }
GET ApplicationContainer the IContainer {public; Private SET;} public IServiceProvider AutoFacRegister (IServiceCollection Services) { var Builder = new new ContainerBuilder (); // Very Import // returns normally does not replace the original IServiceProvider IServicePrivder. Custom ServiceScopeFactory also need to ensure that your custom is ServiceProvider RequestServices returned. // See detailed https: // www.cnblogs.com/artech/p/3rd-party-di-integration.html // here autofac made a special deal with builder.Populate (Services); builder.RegisterType <MemoryBookDAL> ( ) .as <IBookDAL> () .SingleInstance (); builder.RegisterType<TestPermissionCheckService>().As<IPermissionCheckService>().SingleInstance(); builder.RegisterType<PermissionCheckAuthorizationHandler>().As<IAuthorizationHandler>(); builder.RegisterType<DefaultExceptionFilterAttribute>(); builder.RegisterType<GlobalApiLoggingMiddleware>(); builder.RegisterType<GlobalExceptionMiddleware>(); ApplicationContainer = builder.Build(); return new AutofacServiceProvider(ApplicationContainer); }