Abp 的 DI 容器是基于 Microsoft 的依赖注入扩展库(Microsoft.Extensions.DependencyInjection nuget包)开发的。因此,它的文档在 Abp 中也是有效的。 Abp 中可以使用 Autofac 替换内置 DI 容器的,以支持属性注入和动态代理(拦截器)。
// File: Startup.cs // ConfigureContainer is where you can register things directly // with Autofac. This runs after ConfigureServices so the things // here will override registrations made in ConfigureServices. // Don't build the container; that gets done for you. If you // need a reference to the container, you need to use the // "Without ConfigureContainer" mechanism shown later. publicvoidConfigureContainer(ContainerBuilder builder) { builder.RegisterModule(new AutofacModule()); }
// File: Startup.cs // ConfigureServices is where you register dependencies. This gets // called by the runtime before the Configure method, below. public IServiceProvider ConfigureServices(IServiceCollection services) { // Add services to the collection. services.AddMvc();
// Create the container builder. var builder = new ContainerBuilder();
// Register dependencies, populate the services from // the collection, and build the container. // // Note that Populate is basically a foreach to add things // into Autofac that are in the collection. If you register // things in Autofac BEFORE Populate then the stuff in the // ServiceCollection can override those things; if you register // AFTER Populate those registrations can override things // in the ServiceCollection. Mix and match as needed. builder.Populate(services); builder.RegisterType<MyType>().As<IMyType>(); this.ApplicationContainer = builder.Build();
// Create the IServiceProvider based on the container. returnnew AutofacServiceProvider(this.ApplicationContainer); }
// File: abp\framework\src\Volo.Abp.Autofac\Autofac\Extensions\DependencyInjection\AutofacRegistration.cs privatestaticvoidRegister(ContainerBuilder builder, IServiceCollection services) { var moduleContainer = services.GetSingletonInstance<IModuleContainer>(); var registrationActionList = services.GetRegistrationActionList();
foreach (var service in services) { if (service.ImplementationType != null) { // Test if the an open generic type is being registered var serviceTypeInfo = service.ServiceType.GetTypeInfo(); if (serviceTypeInfo.IsGenericTypeDefinition) { builder .RegisterGeneric(service.ImplementationType) .As(service.ServiceType) .ConfigureLifecycle(service.Lifetime) .ConfigureAbpConventions(moduleContainer, registrationActionList); } else { builder .RegisterType(service.ImplementationType) .As(service.ServiceType) .ConfigureLifecycle(service.Lifetime) .ConfigureAbpConventions(moduleContainer, registrationActionList); } } elseif (service.ImplementationFactory != null) { var registration = RegistrationBuilder.ForDelegate(service.ServiceType, (context, parameters) => { var serviceProvider = context.Resolve<IServiceProvider>(); return service.ImplementationFactory(serviceProvider); }) .ConfigureLifecycle(service.Lifetime) .CreateRegistration(); //TODO: ConfigureAbpConventions ?