Autofac官網:https://autofac.org/web
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:屬性自動鏈接
ide
/// <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(); }