public static class IServiceCollectionExtension
{
/// <summary>
/// 程序集依赖注入
/// </summary>
/// <param name="services"></param>
/// <param name="assemblyName"></param>
/// <param name="serviceLifetime"></param>
public static void GetAssembly(this IServiceCollection services, string assemblyName, ServiceLifetime serviceLifetime = ServiceLifetime.Singleton)
{
if (!String.IsNullOrEmpty(assemblyName))
{
Assembly assembly = Assembly.Load(assemblyName);
List<Type> ts = assembly.GetTypes().ToList();
var result = new Dictionary<Type, Type[]>();
if (ts != null)
{
var tsAssemblyList = ts.Where(o => o.IsClass && !o.IsAbstract && !o.IsGenericType && o.Name.Contains("Service"));
foreach (var item in tsAssemblyList)
{
var interfaceType = item.GetInterfaces().First();
switch (serviceLifetime)
{
case ServiceLifetime.Scoped:
services.AddScoped(interfaceType, item);
break;
case ServiceLifetime.Singleton:
services.AddSingleton(interfaceType, item);
break;
case ServiceLifetime.Transient:
services.AddTransient(interfaceType, item);
break;
}
}
}
}
}
}