public void AutoRegister(IServiceCollection services, IEnumerable <Assembly> assemblies) { if (services == null) { throw new ArgumentNullException(nameof(services)); } if (assemblies == null) { throw new ArgumentNullException(nameof(assemblies)); } var autoInjectType = typeof(IAutoInject); var autoInjectAsSingletonType = typeof(IAutoInjectAsSingleton); var autoInjectAsScopedType = typeof(IAutoInjectAsScoped); var autoInjectAsTransientType = typeof(IAutoInjectAsTransient); var autoInjectIgnoreType = typeof(IAutoInjectIgnore); var autoBindTypes = assemblies.SelectMany(x => x.ExportedTypes.Where(t => autoInjectType.IsAssignableFrom(t) && !autoInjectIgnoreType.IsAssignableFrom(t) && !t.IsAbstract && !t.IsInterface)).ToList(); foreach (var autoBindType in autoBindTypes) { var bindTypeImplInterfaces = autoBindType.GetInterfaces(); var serviceInterfaces = bindTypeImplInterfaces.Where(t => t != autoInjectType && t != autoInjectAsSingletonType && t != autoInjectAsScopedType && t != autoInjectAsTransientType).ToList(); if (autoInjectAsSingletonType.IsAssignableFrom(autoBindType)) { //bind self services.AddSingleton(autoBindType); AddIfNotExist(autoBindType, autoBindType, ServiceLifetime.Singleton); foreach (var serviceInterface in serviceInterfaces) { if (!IgnoreServiceInterfaces.Contains(serviceInterface)) { services.AddSingleton(serviceInterface, sp => sp.GetService(autoBindType)); AddIfNotExist(autoBindType, serviceInterface, ServiceLifetime.Singleton); } } continue; } if (autoInjectAsScopedType.IsAssignableFrom(autoBindType)) { //bind self services.AddScoped(autoBindType); AddIfNotExist(autoBindType, autoBindType, ServiceLifetime.Scoped); foreach (var serviceInterface in serviceInterfaces) { if (!IgnoreServiceInterfaces.Contains(serviceInterface)) { services.AddScoped(serviceInterface, sp => sp.GetService(autoBindType)); AddIfNotExist(autoBindType, serviceInterface, ServiceLifetime.Scoped); } } continue; } //default will use IAutoInjectAsTransient //bind self services.AddTransient(autoBindType); AddIfNotExist(autoBindType, autoBindType, ServiceLifetime.Transient); foreach (var serviceInterface in serviceInterfaces) { if (!IgnoreServiceInterfaces.Contains(serviceInterface)) { services.AddTransient(serviceInterface, autoBindType); AddIfNotExist(autoBindType, serviceInterface, ServiceLifetime.Transient); } } } }
public MyLifetimeRegistry() { IgnoreServiceInterfaces.Add(typeof(IDisposable)); }