Files
EmailBill/Common/ServiceExtension.cs
孙诚 f34457a706
Some checks failed
Docker Build & Deploy / Build Docker Image (push) Failing after 43s
Docker Build & Deploy / Deploy to Production (push) Has been skipped
Docker Build & Deploy / Cleanup Dangling Images (push) Successful in 1s
Docker Build & Deploy / WeChat Notification (push) Successful in 2s
feat: 添加深度复制功能,优化自动分类逻辑;更新周期账单视图以显示下次执行时间
2026-01-10 18:04:27 +08:00

92 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.
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
namespace Common;
public static class TypeExtensions
{
/// <summary>
/// 深度复制对象属性到目标对象
/// </summary>
public static T? DeepClone<T>(this T source)
{
var json = System.Text.Json.JsonSerializer.Serialize(source);
return System.Text.Json.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.IsClass && !t.IsAbstract);
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.IsClass && !t.IsAbstract);
foreach (var type in types)
{
var interfaces = type.GetInterfaces()
.Where(i => i.Name.StartsWith("I")
&& i.Namespace == "Repository"
&& !i.IsGenericType); // 排除泛型接口如 IBaseRepository<T>
foreach (var @interface in interfaces)
{
services.AddSingleton(@interface, type);
Console.WriteLine($"注册 Repository: {@interface.Name} -> {type.Name}");
}
}
}
}