齐越消息中心
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

34 lines
1.4 KiB

using Microsoft.Extensions.DependencyInjection;
using System.Reflection;
namespace QYMessageCenter.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<Type> typeList = new List<Type>(); //所有符合注册条件的类集合
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));
}
}
}
}