Files
EmailBill/Common/ServiceExtension.cs
2026-01-18 22:04:56 +08:00

88 lines
2.8 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
namespace Common;
public static class TypeExtensions
{
/// <summary>
/// 深度复制对象属性到目标对象
/// </summary>
public static T? DeepClone<T>(this T source)
{
var json = JsonSerializer.Serialize(source);
return JsonSerializer.Deserialize<T>(json);
}
}
/// <summary>
/// 服务依赖注入扩展
/// </summary>
public static class ServiceExtension
{
/// <summary>
/// 自动扫描并注册服务和仓储
/// </summary>
public static IServiceCollection AddServices(this IServiceCollection services)
{
// 扫描程序集
var serviceAssembly = Assembly.Load("Service");
var repositoryAssembly = Assembly.Load("Repository");
// 注册所有服务实现
RegisterServices(services, serviceAssembly);
// 注册所有仓储实现
RegisterRepositories(services, repositoryAssembly);
return services;
}
private static void RegisterServices(IServiceCollection services, Assembly assembly)
{
var types = assembly.GetTypes()
.Where(t => t is { IsClass: true, IsAbstract: false });
foreach (var type in types)
{
var interfaces = type.GetInterfaces()
.Where(i => i.Name.StartsWith("I") && i.Namespace != null && i.Namespace.StartsWith("Service"));
foreach (var @interface in interfaces)
{
// EmailBackgroundService 必须是 Singleton后台服务其他服务可用 Transient
if (type.Name == "EmailBackgroundService")
{
services.AddSingleton(@interface, type);
}
else if (type.Name == "EmailFetchService")
{
// EmailFetchService 用 Transient避免连接冲突
services.AddTransient(@interface, type);
}
else
{
services.AddSingleton(@interface, type);
}
}
}
}
private static void RegisterRepositories(IServiceCollection services, Assembly assembly)
{
var types = assembly.GetTypes()
.Where(t => t is { IsClass: true, IsAbstract: false });
foreach (var type in types)
{
var interfaces = type.GetInterfaces()
.Where(i => i.Name.StartsWith("I")
&& i is { Namespace: "Repository", IsGenericType: false }); // 排除泛型接口如 IBaseRepository<T>
foreach (var @interface in interfaces)
{
services.AddSingleton(@interface, type);
Console.WriteLine($"注册 Repository: {@interface.Name} -> {type.Name}");
}
}
}
}