feat: Luban.Core初步实现,提供能力:

- RegistService 装饰器实现服务注册
- 下载服务
- 文件服务
- 多线程方法
- 解压缩服务
This commit is contained in:
jackqqq123
2025-09-24 12:07:03 +08:00
parent 6ec2a804ba
commit 369fcbf403
29 changed files with 2024 additions and 11 deletions

View 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)
{
// 注册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;
}
}