ASP.NET CORE 學習之原生DI實現批量註冊

之前使用Autofac的時候,只需一句AsImplementInterfaces()就能夠很輕鬆實現批量註冊功能。而asp.net core內置的DI框架沒有現成的批量註冊方法,考慮到替換Autofac框架過程有些繁瑣,因而本身寫擴展實現了一個簡易的原生DI批量註冊功能框架

Startup.cs擴展asp.net

 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)); this

 

經測試 ,使用擴展批量註冊的方式註冊的服務類正常工做spa

相關文章
相關標籤/搜索