Files
luban_ui_internal/src/LubanHub.Core/ServiceCollectionExtensions.cs

80 lines
2.9 KiB
C#
Raw Normal View History

using LubanHub.Core.Attributes;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
using System.Net.Http;
using System.Reflection;
namespace LubanHub.Core;
/// <summary>
/// Core服务依赖注入扩展
/// </summary>
public static class ServiceCollectionExtensions
{
/// <summary>
/// 添加Core服务 - 通过反射自动发现并注册带有RegistService特性的服务
/// </summary>
public static IServiceCollection AddCoreServices(this IServiceCollection services)
{
// 注册HttpClientCore服务的依赖
services.AddSingleton<HttpClient>();
// 获取当前程序集
var assembly = Assembly.GetExecutingAssembly();
// 发现所有带有RegistService特性的类型
var serviceTypes = assembly.GetTypes()
.Where(type => type.IsClass && !type.IsAbstract && type.GetCustomAttribute<RegistServiceAttribute>() != null)
.Select(type => new
{
Type = type,
Attribute = type.GetCustomAttribute<RegistServiceAttribute>()!
})
.OrderBy(x => x.Attribute.Priority) // 按优先级排序
.ToList();
// 注册服务
foreach (var serviceInfo in serviceTypes)
{
var implementationType = serviceInfo.Type;
var attribute = serviceInfo.Attribute;
// 确定服务接口类型
Type serviceType;
if (attribute.ServiceType != null)
{
// 使用特性指定的服务类型
serviceType = attribute.ServiceType;
}
else
{
// 自动推断:查找实现的第一个接口
var interfaceType = implementationType.GetInterfaces().FirstOrDefault();
if (interfaceType == null)
{
throw new InvalidOperationException($"服务 {implementationType.Name} 没有实现任何接口且未在RegistService特性中指定ServiceType");
}
serviceType = interfaceType;
}
// 根据生命周期注册服务
switch (attribute.Lifetime)
{
case ServiceLifetime.Singleton:
services.AddSingleton(serviceType, implementationType);
break;
case ServiceLifetime.Scoped:
services.AddScoped(serviceType, implementationType);
break;
case ServiceLifetime.Transient:
services.AddTransient(serviceType, implementationType);
break;
default:
throw new ArgumentOutOfRangeException(nameof(attribute.Lifetime), attribute.Lifetime, "不支持的服务生命周期");
}
}
return services;
}
}