在.net core中使用依赖注入是很常见的,最常见的我们会使用以下三种
services.AddScoped<TestIBLL, TestBLL>();
services.AddSingleton<TestIBLL, TestBLL>();
services.AddTransient<TestIBLL, TestBLL>();
当我们的业务层内容不多的时候这样写没有什么问题,但是加入有100个BLL呢,那样一个一
个加会很麻烦,每加一个就要多写一次,而且容易忘记漏掉。
那么我们的需求是让希望能够实现批量注入,并且可以按照不同的生命周期去实现自动注入,以避免每加一个业务类,就要写一次services.AddScoped<>();
我将通过反射来实现它。
周期 AddScoped AddSingleton AddTransient
/// <summary>
/// Add Scoped
/// </summary>
/// <param name="services"></param>
/// <param name="interfaceAssembly"></param>
/// <param name="implementAssembly"></param>
public static void AddScoped(this IServiceCollection services, Assembly interfaceAssembly, Assembly implementAssembly)
{
var interfaces = interfaceAssembly.GetTypes().Where(t => t.IsInterface);
var implements = implementAssembly.GetTypes();
foreach (var item in interfaces)
{
var type = implements.FirstOrDefault(x => item.IsAssignableFrom(x));
if (type != null)
{
services.AddScoped(item, type);
}
}
}
/// <summary>
/// Add AddSingleton
/// </summary>
/// <param name="services"></param>
/// <param name="interfaceAssembly"></param>
/// <param name="implementAssembly"></param>
public static void AddSingleton(this IServiceCollection services, Assembly interfaceAssembly, Assembly implementAssembly)
{
var interfaces = interfaceAssembly.GetTypes().Where(t => t.IsInterface);
var implements = implementAssembly.GetTypes();
foreach (var item in interfaces)
{
var type = implements.FirstOrDefault(x => item.IsAssignableFrom(x));
if (type != null)
{
services.AddSingleton(item, type);
}
}
}
/// <summary>
/// Add AddTransient
/// </summary>
/// <param name="services"></param>
/// <param name="interfaceAssembly"></param>
/// <param name="implementAssembly"></param>
public static void AddTransient(this IServiceCollection services, Assembly interfaceAssembly, Assembly implementAssembly)
{
var interfaces = interfaceAssembly.GetTypes().Where(t => t.IsInterface);
var implements = implementAssembly.GetTypes();
foreach (var item in interfaces)
{
var type = implements.FirstOrDefault(x => item.IsAssignableFrom(x));
if (type != null)
{
services.AddTransient(item, type);
}
}
}
调用
services.AddTransient(Assembly.Load("xxx.IBll"), Assembly.Load("xxx.Bll"));