namespace Application.Extensions; /// /// Application层服务注册扩展 /// public static class ServiceCollectionExtensions { /// /// 注册所有Application层服务 /// public static IServiceCollection AddApplicationServices(this IServiceCollection services) { // 获取Application层程序集 var assembly = typeof(ServiceCollectionExtensions).Assembly; // 自动注册所有以"Application"结尾的类 // 匹配接口规则: IXxxApplication -> XxxApplication var applicationTypes = assembly.GetTypes() .Where(t => t.IsClass && !t.IsAbstract && t.Name.EndsWith("Application")) .ToList(); foreach (var implementationType in applicationTypes) { // 查找对应的接口 IXxxApplication var interfaceType = implementationType.GetInterfaces() .FirstOrDefault(i => i.Name == $"I{implementationType.Name}"); if (interfaceType != null) { services.AddScoped(interfaceType, implementationType); } else { // 如果没有接口,直接注册实现类 services.AddScoped(implementationType); } } return services; } }