123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- 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<T>(this IServiceCollection services)
- {
- var componentsAdded = 0;
- //单例组件
- var siLogger = services.BuildServiceProvider().GetService<ILogger<IAssemblyInjectSingleton>>();
- 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<ILogger<IAssemblyInjectTransient>>();
- 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<ILogger<AssemblyInjectSyncStartStopWorker<T>>>();
- logger.LogWarning("Skip: No found any AssemblyInject components");
- }
- else
- {
- //自动启停Worker
- services.AddHostedService<AssemblyInjectSyncStartStopWorker<T>>();
- }
- }
- }
- }
|