2021-04-14

asp.net core 批量依赖注入服务

好运先生的头像

看园子里netcore的文章都是简单的注入几个服务的例子,在项目中肯定不会一行一行的写注册服务的代码,参考网上,找到一些解决方案,根据自己实际需求进行更改,特记录下来

先创建一个 Startup.cs 扩展类,对IServiceCollection进行扩展

 public static class IServiceCollectionExtenions {  /// <summary>  /// 获取程序集中的类  /// </summary>  /// <param name="assemblyName">程序集名</param>  /// <returns></returns>  private static Dictionary<Type, Type> GetClassName(string assemblyName)  {   var result = new Dictionary<Type, Type>();   if (!string.IsNullOrWhiteSpace(assemblyName))   {    //排除程序程序集中的接口、私有类、抽象类    Assembly assembly = Assembly.Load(assemblyName);    var typeList = assembly.GetTypes().Where(t => !t.IsInterface && !t.IsSealed && !t.IsAbstract).ToList();    //历遍程序集中的类    foreach (var item in typeList)    {     //查找当前类继承且包含当前类名的接口     var interfaceType = item.GetInterfaces().Where(o => o.Name.Contains(item.Name)).FirstOrDefault();     if (interfaceType != null)     {      //把当前类和继承接口加入Dictionary      result.Add(item, interfaceType);     }    }   }   return result;  }  /// <summary>  /// 批量注册  /// </summary>  /// <param name="services"></param>  /// <param name="assemblyName">程序集名</param>  /// <param name="lifetime">服务生命周期</param>  public static void BatchRegisterService(this IServiceCollection services, string assemblyName, ServiceLifetime lifetime = ServiceLifetime.Scoped)  {   foreach (var item in GetClassName(assemblyName))   {    //根据生命周期注册    switch (lifetime)    {     case ServiceLifetime.Scoped:      services.AddScoped(item.Value, item.Key);      break;     case ServiceLifetime.Singleton:      services.AddSingleton(item.Value, item.Key);      break;     case ServiceLifetime.Transient:      services.AddTransient(item.Value, item.Key);      break;    }   }  } } 

然后在 Startup.cs 中服务注册

 public void ConfigureServices(IServiceCollection services) {  services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);  #region 依赖注册
//泛型注册 services.AddScoped(typeof(IRepository<>), typeof(Repository<>)); services.AddScoped<IRepositoryFactory, RepositoryFactory>(); //按程序集名称批量注册 services.BatchRegisterService("Com.Service");

No comments:

Post a Comment