You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

214 lines
6.3 KiB

using Magicodes.ExporterAndImporter.Core;
using Magicodes.ExporterAndImporter.Excel;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
using SqlSugar;
using System;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Wood.AutoJob;
using Wood.Cache;
using Wood.Data.Repository;
using Wood.Entity;
using Wood.EventBus;
using Wood.MemoryCache;
using Wood.RedisCache;
using Wood.Util;
namespace Wood.Admin.WebApi
{
/// <summary>
/// 服务拓展
/// </summary>
public static class ServiceCollectionExtensions
{
/// <summary>
/// 扫描指定程序集中的所有类型,并根据其实现的生命周期接口自动注册到DI容器中。
/// </summary>
/// <param name="services">服务集合</param>
/// <param name="assemblies">要扫描的程序集数组</param>
public static void ScanAndRegisterLifeTimes(this IServiceCollection services, params Assembly[] assemblies)
{
var lifeTimeServices = typeof(ILifeTimeService);
foreach (var assembly in assemblies)
{
// 获取实现了 ILifeTimeService 的非抽象类
var types = assembly.GetTypes()
.Where(t => !t.IsAbstract && t.IsClass && lifeTimeServices.IsAssignableFrom(t));
foreach (var type in types)
{
// 查找实现了哪些生命周期接口
var lifeTimeInterfaces = type.GetInterfaces()
.Where(i => i != lifeTimeServices && lifeTimeServices.IsAssignableFrom(i))
.ToList();
if (!lifeTimeInterfaces.Any())
{
continue; // 如果没有实现任何生命周期接口,则跳过此类型
}
// 根据第一个匹配的生命周期接口注册服务
var lifeTimeInterface = lifeTimeInterfaces.First();
if (typeof(ITransient).IsAssignableFrom(lifeTimeInterface))
{
services.AddTransient(type, type);
}
else if (typeof(IScoped).IsAssignableFrom(lifeTimeInterface))
{
services.AddScoped(type, type);
}
else if (typeof(ISingleton).IsAssignableFrom(lifeTimeInterface))
{
services.AddSingleton(type, type);
}
}
}
}
#region eventbus 初始化
public static IServiceCollection AddEventBus(this IServiceCollection services)
{
services.AddSingleton<IEventBus, InMemoryEventBus>();
return services;
}
/// <summary>
/// 自动注册所有订阅事件
/// </summary>
/// <param name="serviceProvider"></param>
public static void UseEventBus(this IApplicationBuilder app, Assembly[] assemblies)
{
var eventBus = GlobalContext.ServiceProvider!.GetRequiredService<IEventBus>();
foreach (var assembly in assemblies)
{
var types = assembly.GetTypes()
.Where(t => t.IsClass && !t.IsAbstract)
.SelectMany(t => t.GetInterfaces(), (t, i) => new { Type = t, Interface = i })
.Where(x => x.Interface.IsGenericType && x.Interface.GetGenericTypeDefinition() == typeof(IIntegrationEventHandler<>));
foreach (var type in types)
{
var eventType = type.Interface.GetGenericArguments()[0];
var handlerType = type.Type;
var handlerInstance = (dynamic)GlobalContext.ServiceProvider!.GetService(handlerType)!;
var eventName = eventType.Name;
var subscribeMethod = typeof(InMemoryEventBus).GetMethod("Subscribe")!.MakeGenericMethod(eventType, handlerType);
subscribeMethod.Invoke(eventBus, new object[] { handlerInstance });
}
}
}
#endregion
#region autoJob 初始化
public static void UseAutoJob(this IApplicationBuilder app)
{
Task.Run(async () =>
{
if (GlobalContext.SystemConfig!.RunAutoJob)
{
//延迟 5s
await Task.Delay(5 * 1000);
try
{
AutoJobCenter jobCenter = new AutoJobCenter();
jobCenter.ScanJob();
await jobCenter.AddScheduleJob();
}
catch (Exception ex)
{
Log.Error(ex, "初始化自动job失败!");
}
}
});
}
#endregion
#region sqlsugar初始化
// <summary>
/// SqlSugar 上下文初始化
/// </summary>
/// <param name="services"></param>
public static void AddSqlSugar(this IServiceCollection services, IConfiguration configuration)
{
// 自定义 SqlSugar 雪花ID算法
SnowFlakeSingle.WorkId = GlobalContext.SystemConfig!.SnowFlakeWorkerId;
if (Enum.TryParse(GlobalContext.SystemConfig.DBProvider, true, out SqlSugar.DbType dbType))
{
services.AddSingleton<ISqlSugarClient>(s =>
{
SqlSugarScope sqlSugar = new SqlSugarScope(new ConnectionConfig()
{
ConnectionString = GlobalContext.SystemConfig.DBConnectionString,
DbType = dbType,
IsAutoCloseConnection = true
}, db =>
{
SqlSugarDbContext.SetDbDiffLog(db.Context);
SqlSugarDbContext.SetDbAop(db.Context);
});
return sqlSugar;
}); // 单例注册
services.AddScoped(typeof(SqlSugarRepository<>)); // 仓储注册
services.AddTransient<IUnitOfWork, SqlSugarUnitOfWork>(); // 事务与工作单元注册
}
else
throw Oops.Oh("不支持的数据库类型!");
}
/// <summary>
/// 初始化数据库
/// </summary>
/// <param name="app"></param>
public static void UseSqlSugar(this IApplicationBuilder app)
{
var sqlsugar = GlobalContext.ServiceProvider!.GetService<ISqlSugarClient>();
// 初始化数据库表结构及种子数据
SqlSugarDbContext.InitDatabase(sqlsugar!);
}
#endregion
/// <summary>
/// 开启缓存
/// </summary>
/// <param name="services"></param>
/// <returns></returns>
public static IServiceCollection AddCache(this IServiceCollection services)
{
switch (GlobalContext.SystemConfig!.CacheProvider)
{
case "Redis": services.AddSingleton<ICache, RedisCacheImp>(); break;
default:
case "Memory": services.AddSingleton<ICache, MemoryCacheImp>(); break;
}
;
return services;
}
/// <summary>
/// Magicodes
/// 导入导出
/// </summary>
/// <param name="services"></param>
/// <returns></returns>
public static IServiceCollection AddMagicodesIE(this IServiceCollection services)
{
// 注册 Excel 导出器
services.AddSingleton<IExcelExporter, ExcelExporter>();
services.AddSingleton<IExcelImporter, ExcelImporter>();
// 如果需要支持其他格式(如 PDF、Word 等),可以在这里添加相应的导出器
// services.AddSingleton<IExporter, PdfExporter>();
// services.AddSingleton<IExporter, WordExporter>();
return services;
}
}
}