.net core 3.1添加Autofac容器
交流QQ群:555913397 有什么问题可以加群大家一起交流
1.引用nuget包
1.1 Autofac
1.2 Autofac.Extensions.DependencyInjection
2. 在Program.cs添加Autofac服务提供工厂
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
}).UseServiceProviderFactory(new AutofacServiceProviderFactory());
2.1添加这段代码UseServiceProviderFactory(new AutofacServiceProviderFactory())
3.在Startup.cs添加容器注册
pulic void ConfigureContainer(ContainerBuilder builder){
//这里添加注册容器,可以直接注册也可以注册Module
//1.注册Module方式,下面的AtuofacModule是自己写的类,名字可以随意取.
builder.RegisterModule(new AutofacModule());
//2.直接注册容器
builder.RegisterType<People>().As<IPeople>().AsImplementedInterfaces();
//2.1注册程序集
Assembly serviceAssembly = Assembly.Load("程序集名称");
Assembly InterfaceAssembly = Assembly.Load("程序集名称");
builder.RegisterAssemblyTypes(serviceAssembly,InterfaceAssembly)
.where(x=>x.Name.EndWith("AppService",StringComparison.OrdinalIgnoreCase)
.AsImplementedInterfaces();
}
4.Autofac Module类
public class AutofacModule : Module{
protected ovrride void Load(ContainerBuilder builder){
//这里添加注册容器,可以直接注册也可以注册Module
//1.注册Module方式,下面的AtuofacModule是自己写的类,名字可以随意取.
builder.RegisterModule(new AutofacModule());
//2.直接注册容器
builder.RegisterType<People>().As<IPeople>().AsImplementedInterfaces();
//2.1注册程序集
Assembly serviceAssembly = Assembly.Load("程序集名称");
Assembly InterfaceAssembly = Assembly.Load("程序集名称");
builder.RegisterAssemblyTypes(serviceAssembly,InterfaceAssembly)
.where(x=>x.Name.EndWith("AppService",StringComparison.OrdinalIgnoreCase)
.AsImplementedInterfaces();
}
}