.net core中使用autofac进行IOC

时间:2021-06-03 20:11:39

.net Core中自带DI是非常简单轻量化的,但是如果批量注册就得扩展,下面使用反射进行批量注册的

 public void AddAssembly(IServiceCollection services,string assemblyName)
{
if (!string.IsNullOrEmpty(assemblyName))
{
var assembly = Assembly.Load(assemblyName);
var ts = assembly.GetTypes().Where(n => n.IsClass && !n.IsAbstract && !n.IsGenericType).ToList();
foreach (var item in ts.Where(s => !s.IsInterface))
{
var interfaceType = item.GetInterfaces();
if (interfaceType.Length == )
services.AddScoped(interfaceType[], item);
if (interfaceType.Length > )
services.AddScoped(interfaceType[], item);
}
}
}

下面是将自带的DI换成AutoFac进行批量DI

(NuGet引入Autofac,Autofac.Configuration,Autofac.Extensions.DependencyInjection)

 public class AutofacModule : Autofac.Module
{
//重写Autofac管道Load方法,在这里注册注入
protected override void Load(ContainerBuilder builder)
{
//注册Service中的对象,Service中的类要以Service结尾,否则注册失败
builder.RegisterAssemblyTypes(Assembly.Load("CoreDemo")).Where(a => a.Name.EndsWith("Service")).AsImplementedInterfaces();
}
}
 public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.Configure<ConnectionOptions>(_configuration.GetSection("ConnectionStrings")); #region 注册Autofac
//实例化Autofac容器
var builder = new ContainerBuilder();
//将Services中的服务填充到Autofac中
builder.Populate(services);
//新模块组件注册
builder.RegisterModule<AutofacModule>();
//创建容器
var Container = builder.Build();
//Autofac接管.net core内置DI容器
return new AutofacServiceProvider(Container);
#endregion
}

相关文章