using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using WarcViewerBlazorWinForm.Library.AssemblyInject.Interfaces; using WarcViewerBlazorWinForm.Library.AssemblyInject.Services; namespace WarcViewerBlazorWinForm.Library.AssemblyInject { public static class AssemblyInjectConfigure { public static void AddAssemblyInject(this IServiceCollection services) { var componentsAdded = 0; //单例组件 var siLogger = services.BuildServiceProvider().GetService>(); foreach (var svcType in typeof(T).Assembly.GetTypes() .Where(typeof(IAssemblyInjectSingleton).IsAssignableFrom) .Where(p => p.IsInterface == false && p.IsAbstract == false) .OrderBy(p => p.Name)) { var gsi = svcType.GetInterfaces().Where(p => p.IsGenericType && p.GetGenericTypeDefinition() == typeof(IAssemblyInjectSingleton<>)).ToArray(); if (gsi.Length == 0) { siLogger.LogInformation($"AddSingleton {svcType.Name} @ {svcType.Namespace}"); services.AddSingleton(svcType); ++componentsAdded; } else { foreach (var type in gsi) { var addAs = type.GetGenericArguments().First()!; siLogger.LogInformation($"AddSingleton {svcType.Name} @ {svcType.Namespace} as {addAs.Name}"); services.AddSingleton(addAs, svcType); ++componentsAdded; } } } //Transient组件 var tsLogger = services.BuildServiceProvider().GetService>(); foreach (var svcType in typeof(T).Assembly.GetTypes() .Where(typeof(IAssemblyInjectTransient).IsAssignableFrom) .Where(p => p.IsInterface == false && p.IsAbstract == false)) { var gsi = svcType.GetInterfaces().Where(p => p.IsGenericType && p.GetGenericTypeDefinition() == typeof(IAssemblyInjectTransient<>)).ToArray(); if (gsi.Length == 0) { tsLogger.LogInformation($"AddTransient {svcType.FullName}"); services.AddTransient(svcType); ++componentsAdded; } else { foreach (var type in gsi) { var addAs = type.GetGenericArguments().First()!; siLogger.LogInformation($"AddTransient {svcType.Name} @ {svcType.Namespace} as {addAs.Name}"); services.AddTransient(addAs, svcType); ++componentsAdded; } } } if (componentsAdded == 0) { var logger = services.BuildServiceProvider().GetService>>(); logger.LogWarning("Skip: No found any AssemblyInject components"); } else { //自动启停Worker services.AddHostedService>(); } } } }