-
Notifications
You must be signed in to change notification settings - Fork 52
0.QucikStart
俞正东 edited this page May 26, 2023
·
3 revisions
请参考官方教程(里面详细区分了ASP.NET Core 1.1 - 2.2 和 ASP.NET Core 3+ 的使用方式):
https://autofaccn.readthedocs.io/en/latest/integration/aspnetcore.html?highlight=aspnetcore
按照第一步搞定后
var builder = WebApplication.CreateBuilder(args);
// 设置使用autofac作为DI容器
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
// 设置DI容器 添加注解功能
builder.Host.ConfigureContainer<ContainerBuilder>((c, containerBuilder) =>
{
// 在这里 在这里 在这里
containerBuilder.RegisterModule(new AutofacAnnotationModule());
});
// 如果希望设置Controller实例的生成也交给autofac
// builder.Host.ConfigureServices(services => { services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>());
// 如果希望PageModel的实例的生成也交给autofac
// builder.Host.ConfigureServices(services => { services.Replace(ServiceDescriptor.Transient<IPageModelActivatorProvider, ServiceBasedPageModelActivatorProvider>()); });
});
// 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 by the factory.
public void ConfigureContainer(ContainerBuilder builder)
{
// 在这里 在这里 在这里
builder.RegisterModule(new AutofacAnnotationModule());
}
// ConfigureServices is where you register dependencies and return an `IServiceProvider` implemented by `AutofacServiceProvider`.
// This is the old, not recommended way, and is NOT SUPPORTED in ASP.NET Core 3.0+.
public IServiceProvider ConfigureServices(IServiceCollection services)
{
// Add services to the collection
services.AddOptions();
// Create a container-builder and register dependencies
var builder = new ContainerBuilder();
// Populate the service-descriptors added to `IServiceCollection`
// BEFORE you add things to Autofac so that the Autofac
// registrations can override stuff in the `IServiceCollection`
// as needed
builder.Populate(services);
// 在这里 在这里 在这里
builder.RegisterModule(new AutofacAnnotationModule());
AutofacContainer = builder.Build();
// this will be used as the service-provider for the application!
return new AutofacServiceProvider(AutofacContainer);
}
- 空的构造方法 默认会自动加载你项目里面的所有引用
- 传Assembly(一个或多个)进去,仅仅扫描加载指定的Assembly