.net6引入autofac框架
时间:2022-10-29 11:23:15|栏目:.NET代码|点击: 次
引入NuGet
注册Autofac
在Program的var app = builder.Build();前加上这段代码
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory()); builder.Host.ConfigureContainer<ContainerBuilder>(builder => { builder.RegisterType<LogRecordsService>().As<ILogRecordsService>(); });
自动注册一个类库的服务
在Program注入autofac
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory()); builder.Host.ConfigureContainer<ContainerBuilder>(builder => { Assembly assembly = Assembly.Load(ServiceCore.GetAssemblyName()); builder.RegisterAssemblyTypes(assembly) .AsImplementedInterfaces() .InstancePerDependency(); });
在要注册的类库下的某个类中,写一个方法
public static class ServiceCore { /// <summary> /// 获取程序集名称 /// </summary> /// <returns></returns> public static string GetAssemblyName() { return Assembly.GetExecutingAssembly().GetName().Name; } }