mirror of
https://github.com/jackqqq123/luban_ui_internal.git
synced 2025-11-15 21:58:48 +08:00
feat: Luban.Core初步实现,提供能力:
- RegistService 装饰器实现服务注册 - 下载服务 - 文件服务 - 多线程方法 - 解压缩服务
This commit is contained in:
80
src/LubanHub.Core/ServiceCollectionExtensions.cs
Normal file
80
src/LubanHub.Core/ServiceCollectionExtensions.cs
Normal file
@@ -0,0 +1,80 @@
|
||||
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)
|
||||
{
|
||||
// 注册HttpClient(Core服务的依赖)
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user