引入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;
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。