标签:var das ati where 实现 映射 名称 color 分享
1.获取实现类程序集方法
1 public class RuntimeHelper 2 { 3 //通过程序集的名称加载程序集 4 public static Assembly GetAssemblyByName(string assemblyName) 5 { 6 return AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(assemblyName)); 7 } 8 }
2.遍历实现类,批量注入映射关系
1 public static void AddAssembly(this IServiceCollection service, string assemblyName 2 ,ServiceLifetime serviceLifetime = ServiceLifetime.Scoped) 3 { 4 var assembly = RuntimeHelper.GetAssemblyByName(assemblyName); 5 6 var types = assembly.GetTypes(); 7 var list = types.Where(u => u.IsClass && !u.IsAbstract && !u.IsGenericType).ToList(); 8 9 foreach (var type in list) 10 { 11 var interfaceList = type.GetInterfaces(); 12 if (interfaceList.Any()) 13 { 14 var inter = interfaceList.First(); 15 16 switch (serviceLifetime) 17 { 18 case ServiceLifetime.Transient: 19 service.AddTransient(inter, type); 20 break; 21 case ServiceLifetime.Scoped: 22 service.AddScoped(inter, type); 23 break; 24 case ServiceLifetime.Singleton: 25 service.AddSingleton(inter, type); 26 break; 27 28 } 29 service.AddScoped(inter, type); 30 } 31 } 32 } 33 }
3.在Startup类中使用
4.这样就实现了类似于autofac的功能,其实.net core自己的依赖注入容器挺好的
标签:var das ati where 实现 映射 名称 color 分享
原文地址:https://www.cnblogs.com/Spinoza/p/9984489.html