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 { /// /// 服务拓展 /// public static class ServiceCollectionExtensions { /// /// 扫描指定程序集中的所有类型,并根据其实现的生命周期接口自动注册到DI容器中。 /// /// 服务集合 /// 要扫描的程序集数组 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(); return services; } /// /// 自动注册所有订阅事件 /// /// public static void UseEventBus(this IApplicationBuilder app, Assembly[] assemblies) { var eventBus = GlobalContext.ServiceProvider!.GetRequiredService(); 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初始化 // /// SqlSugar 上下文初始化 /// /// 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(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(); // 事务与工作单元注册 } else throw Oops.Oh("不支持的数据库类型!"); } /// /// 初始化数据库 /// /// public static void UseSqlSugar(this IApplicationBuilder app) { var sqlsugar = GlobalContext.ServiceProvider!.GetService(); // 初始化数据库表结构及种子数据 SqlSugarDbContext.InitDatabase(sqlsugar!); } #endregion /// /// 开启缓存 /// /// /// public static IServiceCollection AddCache(this IServiceCollection services) { switch (GlobalContext.SystemConfig!.CacheProvider) { case "Redis": services.AddSingleton(); break; default: case "Memory": services.AddSingleton(); break; } ; return services; } /// /// Magicodes /// 导入导出 /// /// /// public static IServiceCollection AddMagicodesIE(this IServiceCollection services) { // 注册 Excel 导出器 services.AddSingleton(); services.AddSingleton(); // 如果需要支持其他格式(如 PDF、Word 等),可以在这里添加相应的导出器 // services.AddSingleton(); // services.AddSingleton(); return services; } } }