ASP.NET CORE 学习之原生DI实现批量注册

以前使用Autofac的时候,只需一句AsImplementInterfaces()就可以很轻松实现批量注册功能。而asp.net core内置的DI框架没有现成的批量注册方法,考虑到替换Autofac框架过程有些繁琐,于是自己写扩展实现了一个简易的原生DI批量注册功能

Startup.cs扩展

 1 public static class StartUpExtenions
 2     {
 3         /// <summary>
 4         /// 批量注册服务
 5         /// </summary>
 6         /// <param name="services">DI服务</param>
 7         /// <param name="assemblys">需要批量注册的程序集集合</param>
 8         /// <param name="baseType">基础类/接口</param>
 9         /// <param name="serviceLifetime">服务生命周期</param>
10         /// <returns></returns>
11         public static IServiceCollection BatchRegisterService(this IServiceCollection services, Assembly[] assemblys, Type baseType, ServiceLifetime serviceLifetime = ServiceLifetime.Singleton)
12         {
13             List<Type> typeList = new List<Type>();  //所有符合注册条件的类集合
14             foreach (var assembly in assemblys)
15             {
16                 //筛选当前程序集下符合条件的类
17                 var types = assembly.GetTypes().Where(t => !t.IsInterface && !t.IsSealed && !t.IsAbstract && baseType.IsAssignableFrom(t));
18                 if (types != null && types.Count() > 0)
19                     typeList.AddRange(types);
20             }
21             if (typeList.Count() == 0)
22                 return services;
23 
24             var typeDic = new Dictionary<Type, Type[]>(); //待注册集合
25             foreach (var type in typeList)
26             {
27                 var interfaces = type.GetInterfaces();   //获取接口
28                 typeDic.Add(type, interfaces);
29             }
30             if (typeDic.Keys.Count() > 0)
31             {
32                 foreach (var instanceType in typeDic.Keys)
33                 {
34                     foreach (var interfaceType in typeDic[instanceType])
35                     {
36                         //根据指定的生命周期进行注册
37                         switch (serviceLifetime)
38                         {
39                             case ServiceLifetime.Scoped:
40                                 services.AddScoped(interfaceType, instanceType);
41                                 break;
42                             case ServiceLifetime.Singleton:
43                                 services.AddSingleton(interfaceType, instanceType);
44                                 break;
45                             case ServiceLifetime.Transient:
46                                 services.AddTransient(interfaceType, instanceType);
47                                 break;
48                         }
49                     }
50                 }
51             }
52             return services;
53         }
54     }

 

在ConfigureServices方法中调用批量注册

 1 services.BatchRegisterService(new Assembly[] { Assembly.GetExecutingAssembly(), Assembly.Load("Test.DAL") }, typeof(IDependency)); 

 

经测试 ,使用扩展批量注册的方式注册的服务类正常工作

posted on 2019-01-14 13:13  #山鸡  阅读(1319)  评论(5编辑  收藏

导航