安装 Autofac.Extensions.DependencyInjection;Autofac
1.在Startup.cs里面添加
public void ConfigureContainer(ContainerBuilder containerBuilder)
{
containerBuilder.RegisterModule<ConfigureAutofac>();
}
2.新建类ConfigureAutofac.cs
public class ConfigureAutofac : Autofac.Module
{
protected override void Load(ContainerBuilder builder) {
var baseTypeDomain = typeof(IDependency); //IDependency 空的接口,所有接口继承它就可以了
//自动注册接口
builder.RegisterAssemblyTypes(assembly)
.Where(b => b.GetInterfaces().Any(c => c == baseTypeDomain && b != baseTypeDomain))
.AsImplementedInterfaces()
.SingleInstance();
}
}
3.修改Program.cs
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
}).UseServiceProviderFactory(new AutofacServiceProviderFactory());//改用Autofac来实现依赖注入;