以前使用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));
經測試 ,使用擴展批量注冊的方式注冊的服務類正常工作