1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- using Bmp.Core.Common.AssemblyInject.Interfaces;
- using Bmp.Core.Common.AssemblyInject.Services;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Logging;
- namespace Bmp.Core.Common.AssemblyInject;
- internal class AssemblyInject { }
- public static class AssemblyInjectConfigure
- {
- public static void AddAssemblyInject<T>(this IServiceCollection services)
- {
- var aiLogger = services.BuildServiceProvider().GetService<ILogger<AssemblyInject>>();
- aiLogger?.LogInformation("Discovering components...");
- 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.FullName}");
- services.AddSingleton(svcType);
- ++componentsAdded;
- }
- else
- {
- foreach (var type in gsi)
- {
- var addAs = type.GetGenericArguments().First()!;
- siLogger?.LogInformation($"AddSingleton {svcType.FullName} as {addAs.FullName}");
- 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.FullName} as {addAs.FullName}");
- 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
- {
- aiLogger?.LogInformation($"Discovered number of components:{componentsAdded}");
- //自动启停Worker
- services.AddHostedService<AssemblyInjectSyncStartStopWorker<T>>();
- }
- }
- }
|