lg_backend/langguanApi/Extensions/AutoDI/ServicesAutoInjectionExtens...

71 lines
2.9 KiB
C#
Raw Permalink Normal View History

2024-05-20 14:56:49 +00:00
using System.Reflection;
namespace langguanApi.Extensions.AutoDI
{
/// <summary>
/// 自动注入
/// </summary>
public static class AutoDIExtensions
{
/// <summary>
///
/// </summary>
/// <param name="serviceCollection"></param>
/// <returns></returns>
public static IServiceCollection ServicesAutoInjectionExtension(this IServiceCollection serviceCollection)
{
var directory = AppDomain.CurrentDomain.BaseDirectory;
var types = Directory.GetFiles(directory, "*.dll", SearchOption.TopDirectoryOnly)
.Select(Assembly.LoadFrom)
.SelectMany(a => a.GetTypes());
Injection(serviceCollection, types);
return serviceCollection;
}
/// <summary>
/// 服务自动注入
/// </summary>
/// <param name="serviceCollection">需要自动注入服务的服务集合</param>
/// <param name="selector">应用于每个Assembly的筛选函数</param>
/// <exception cref="ArgumentOutOfRangeException">指定的注入类型不在可注入的范围内</exception>
/// <exception cref="NoImplementationInterfaceException">指定注入的类型未实现任何服务</exception>
/// <exception cref="ArgumentException">输入的参数错误1、注入的类型未实现指定的服务。2、指定的服务不是Interface类型</exception>
/// <returns>自动注入服务后的服务集合</returns>
public static IServiceCollection ServicesAutoInjection(this IServiceCollection serviceCollection, Func<Assembly, bool> selector)
{
var directory = AppDomain.CurrentDomain.BaseDirectory;
var types = Directory.GetFiles(directory, "*.dll", SearchOption.TopDirectoryOnly)
.Select(Assembly.LoadFrom)
.Where(selector)
.SelectMany(a => a.GetTypes());
Injection(serviceCollection, types);
return serviceCollection;
}
// 注入逻辑
private static void Injection(IServiceCollection serviceCollection, IEnumerable<Type> types)
{
foreach (var type in types)
{
var attribute = type.GetCustomAttribute<ServiceInjectionAttribute>();
if (attribute == null) continue;
switch (attribute.InjectionType)
{
case InjectionType.Transient:
serviceCollection.AddTransient(type);
break;
case InjectionType.Scoped:
serviceCollection.AddScoped(type);
break;
case InjectionType.Singleton:
serviceCollection.AddSingleton(type);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
}
}