using Microsoft.Extensions.DependencyInjection; using System.Reflection; namespace SBF.Common.Extensions { public static class StartupExtension { public static void BatchRegisterServices(this IServiceCollection serviceCollection, Assembly[] assemblys, Type baseType, ServiceLifetime serviceLifetime = ServiceLifetime.Singleton, bool registerSelf = true) { List typeList = new List(); //所有符合注册条件的类集合 foreach (var assembly in assemblys) { var types = assembly.GetTypes().Where(t => t.IsClass && !t.IsSealed && !t.IsAbstract && baseType.IsAssignableFrom(t)); typeList.AddRange(types); } if (typeList.Count() == 0) return; foreach (var instanceType in typeList) { if (registerSelf) { serviceCollection.Add(new ServiceDescriptor(instanceType, instanceType, serviceLifetime)); continue; } var interfaces = instanceType.GetInterfaces(); if (interfaces != null && interfaces.Length > 0) foreach (var interfaceType in interfaces) serviceCollection.Add(new ServiceDescriptor(interfaceType, instanceType, serviceLifetime)); } } } }