使用Autofac替換掉微軟的DI
本文的項目為ASP.NET Core3.1,傳統三層架構 在這就不過多介紹Autofac,直接上代碼Autofac官網:https://autofac.org/
Program.cs的 IHostBuilder 方法內加上 .UseServiceProviderFactory(new AutofacServiceProviderFactory())(如下圖)
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())//啟用autofac容器
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
在Startup.cs內新增 ConfigureContainer 方法
屬性介紹
RegisterAssemblyTypes:寄存器程序集類型
AsImplementedInterfaces:實現的接口
InstancePerDependency:實例依賴關系
PropertiesAutowired:屬性自動連接
/// <summary>
/// 配置Autofac容器替換微軟的DI
/// </summary>
/// <param name="builder"></param>
public void ConfigureContainer(ContainerBuilder builder)
{
var basePath = AppContext.BaseDirectory;
//DALService所在程序集命名空間
string DALPath = Path.Combine(basePath, "GraduationProject.DAL.dll");
Assembly DAL = Assembly.LoadFrom(DALPath);
//BLLService所在程序集命名空間
string BLLPath = Path.Combine(basePath, "GraduationProject.BLL.dll");
Assembly BLL = Assembly.LoadFrom(BLLPath);
builder.RegisterAssemblyTypes(DAL).InstancePerDependency().PropertiesAutowired();
builder.RegisterAssemblyTypes(BLL).AsImplementedInterfaces().InstancePerDependency().PropertiesAutowired();
}