2019-11-29 12:26:53 +00:00
|
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
2019-12-10 14:47:48 +00:00
|
|
|
|
|
2019-12-10 15:06:51 +00:00
|
|
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
|
using Microsoft.Extensions.DependencyInjection.Extensions;
|
2019-11-29 12:26:53 +00:00
|
|
|
|
using Microsoft.Extensions.Options;
|
|
|
|
|
|
|
|
|
|
namespace ASC.Core.Common.EF
|
|
|
|
|
{
|
|
|
|
|
public class DbContextManager<T> : OptionsManager<T>, IDisposable where T : BaseDbContext, new()
|
|
|
|
|
{
|
|
|
|
|
private Dictionary<string, T> Pairs { get; set; }
|
|
|
|
|
private List<T> AsyncList { get; set; }
|
|
|
|
|
|
|
|
|
|
public IOptionsFactory<T> Factory { get; }
|
|
|
|
|
|
|
|
|
|
public DbContextManager(IOptionsFactory<T> factory) : base(factory)
|
|
|
|
|
{
|
|
|
|
|
Pairs = new Dictionary<string, T>();
|
|
|
|
|
AsyncList = new List<T>();
|
|
|
|
|
Factory = factory;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public override T Get(string name)
|
|
|
|
|
{
|
|
|
|
|
var result = base.Get(name);
|
|
|
|
|
|
|
|
|
|
if (!Pairs.ContainsKey(name))
|
|
|
|
|
{
|
|
|
|
|
Pairs.Add(name, result);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return result;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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();
|
|
|
|
|
}
|
2019-12-10 14:47:48 +00:00
|
|
|
|
|
|
|
|
|
foreach (var v in AsyncList)
|
|
|
|
|
{
|
|
|
|
|
v.Dispose();
|
|
|
|
|
}
|
2019-11-29 12:26:53 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
2019-12-10 15:06:51 +00:00
|
|
|
|
|
|
|
|
|
public static class DbContextManagerExtension
|
|
|
|
|
{
|
|
|
|
|
public static IServiceCollection AddDbContextManagerService<T>(this IServiceCollection services) where T : BaseDbContext, new()
|
|
|
|
|
{
|
|
|
|
|
services.TryAddScoped<DbContextManager<T>>();
|
|
|
|
|
services.TryAddScoped<IConfigureOptions<T>, ConfigureDbContext>();
|
|
|
|
|
services.TryAddScoped<T>();
|
|
|
|
|
|
|
|
|
|
return services;
|
|
|
|
|
}
|
|
|
|
|
}
|
2019-11-29 12:26:53 +00:00
|
|
|
|
}
|