愤怒的南瓜饼 发表于 2023-7-25 10:31:55

使用Autofac进行服务注册,适用版本.Net6(程序集、泛型)

具体的也可以去参考官网:https://autofac.readthedocs.io/en/latest/integration/aspnetcore.html
首先在Program.cs所属的层中引用nuget包:
Autofac.Extensions.DependencyInjection

nuget网址:https://www.nuget.org/packages  可以使用NuGet包管理器进行搜索安装
在Program.cs中加入如下代码:
//注册服务工厂(Autofac)
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureContainer<ContainerBuilder>(container =>
{
   //使用程序集进行注册服务
   container.RegisterAssemblyTypes(Assembly.Load("SmartHealthcare.Application")).AsImplementedInterfaces();
   container.RegisterAssemblyTypes(Assembly.GetExecutingAssembly());
   //泛型注册服务
   container.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>)).InstancePerDependency();
});代码中SmartHealthcare.Application可以替换为具体自己项目中Application层的全名,还有typeof(Repository)和typeof(IRepository)也是同样的道理替换为自己项目中的仓储实现层名称和仓储接口层名称。
 

来源:https://www.cnblogs.com/zkmblog/archive/2023/07/24/17577840.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: 使用Autofac进行服务注册,适用版本.Net6(程序集、泛型)