using System; using System.Collections.Generic; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; namespace ASC.Core.Common.EF { public class BaseDbContextManager : OptionsManager, IDisposable where T : class, IDisposable, IAsyncDisposable, new() { private Dictionary Pairs { get; set; } private List AsyncList { get; set; } public IOptionsFactory Factory { get; } public BaseDbContextManager(IOptionsFactory factory) : base(factory) { Pairs = new Dictionary(); AsyncList = new List(); Factory = factory; } public override T Get(string name) { if (!Pairs.ContainsKey(name)) { Pairs.Add(name, base.Get(name)); } return Pairs[name]; } public T GetNew(string name = "default") { var result = Factory.Create(name); AsyncList.Add(result); return result; } public void Dispose() { foreach (var v in Pairs) { v.Value.Dispose(); } foreach (var v in AsyncList) { v.Dispose(); } } } public class DbContextManager : BaseDbContextManager where T : BaseDbContext, new() { public DbContextManager(IOptionsFactory factory) : base(factory) { } } public class MultiRegionalDbContextManager : BaseDbContextManager> where T : BaseDbContext, new() { public MultiRegionalDbContextManager(IOptionsFactory> factory) : base(factory) { } } public static class DbContextManagerExtension { public static IServiceCollection AddDbContextManagerService(this IServiceCollection services) where T : BaseDbContext, new() { services.TryAddScoped>(); services.TryAddScoped>(); services.TryAddScoped, ConfigureDbContext>(); services.TryAddScoped>, ConfigureMultiRegionalDbContext>(); services.TryAddScoped(); return services; } } }