49 lines
1.9 KiB
C#
49 lines
1.9 KiB
C#
using Service.Implement;
|
|
using System.Reflection;
|
|
|
|
namespace WebAPI
|
|
{
|
|
/// <summary>
|
|
/// 业务服务依赖注入扩展
|
|
/// 约定:Service.Interface 中的 IXxxService 对应 Service.Implement 中的 XxxService
|
|
/// </summary>
|
|
public static class DependencyInjection
|
|
{
|
|
/// <summary>
|
|
/// 自动注册所有业务服务(按命名约定:接口去掉前缀 I 即为实现类名)
|
|
/// 以后在 Service 项目里新增「接口 + 实现」时,无需改动这里,会自动注册
|
|
/// </summary>
|
|
public static IServiceCollection AddBusinessServices(this IServiceCollection services)
|
|
{
|
|
// Service 项目程序集(接口与实现都在同一个程序集里)
|
|
Assembly assembly = typeof(BaseService<>).Assembly;
|
|
|
|
// 所有具体实现类(非抽象、非泛型定义)
|
|
var implTypes = assembly.GetTypes()
|
|
.Where(t => t.IsClass && !t.IsAbstract && !t.IsGenericTypeDefinition)
|
|
.ToList();
|
|
|
|
// 所有接口
|
|
var ifaceTypes = assembly.GetTypes()
|
|
.Where(t => t.IsInterface && !t.IsGenericTypeDefinition)
|
|
.ToList();
|
|
|
|
foreach (var iface in ifaceTypes)
|
|
{
|
|
// 接口名去掉前缀 I,得到期望的实现类名
|
|
string implName = iface.Name.StartsWith("I") ? iface.Name.Substring(1) : iface.Name;
|
|
var impl = implTypes.FirstOrDefault(t => t.Name == implName);
|
|
if (impl != null && iface.IsAssignableFrom(impl))
|
|
{
|
|
services.AddScoped(iface, impl);
|
|
}
|
|
}
|
|
|
|
// 泛型基础服务(IBaseService<> -> BaseService<>)单独注册
|
|
services.AddScoped(typeof(Service.Interface.IBaseService<>), typeof(Service.Implement.BaseService<>));
|
|
|
|
return services;
|
|
}
|
|
}
|
|
}
|