第一次使用autofac,然后net6最新长期支持的,就想着在net6的基础上使用autofac,我对依赖注入理解很差,一知半解的搞了好久。好在有了一点点的头绪,记录下省的以后忘记(突然发现自己以前用过的东西忘了好多……)
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());//覆盖默认的容器工厂。 builder.Host.ConfigureContainer<ContainerBuilder>(builder => { builder.RegisterModule(new AutoFacMoudleReg());//添加注册规则模块儿 });
protected override void Load(ContainerBuilder builder) { string basePath=AppDomain.CurrentDomain.BaseDirectory;//获取程序集路径 //你要注册的服务 Dll路径 var assemblysRepositoryPath = Path.Combine(basePath, "DogRepository"); var assemblysServicesPath = Path.Combine(basePath, "DogService"); //注入仓储 var assemblysRepository = Assembly.LoadFrom(assemblysRepositoryPath); builder.RegisterAssemblyTypes(assemblysRepository) .AsImplementedInterfaces() .PropertiesAutowired() .InstancePerDependency(); //注入服务 var assemblysServices = Assembly.LoadFrom(assemblysServicesPath); builder.RegisterAssemblyTypes(assemblysServices) .AsImplementedInterfaces() .InstancePerDependency() .PropertiesAutowired(); }
如此这样就结束了!