DocSpace-client/common/ASC.Core.Common/EF/Context/DbContextManager.cs

88 lines
2.5 KiB
C#
Raw Normal View History

2019-11-29 12:26:53 +00:00
using System;
using System.Collections.Generic;
2019-12-10 14:47:48 +00:00
2020-02-17 08:58:14 +00:00
using ASC.Common;
2020-04-28 15:11:10 +00:00
using ASC.Common.Logging;
2019-11-29 12:26:53 +00:00
using Microsoft.Extensions.Options;
namespace ASC.Core.Common.EF
{
2019-12-16 14:55:59 +00:00
public class BaseDbContextManager<T> : OptionsManager<T>, IDisposable where T : class, IDisposable, IAsyncDisposable, new()
2019-11-29 12:26:53 +00:00
{
private Dictionary<string, T> Pairs { get; set; }
private List<T> AsyncList { get; set; }
public IOptionsFactory<T> Factory { get; }
2019-12-16 14:55:59 +00:00
public BaseDbContextManager(IOptionsFactory<T> factory) : base(factory)
2019-11-29 12:26:53 +00:00
{
Pairs = new Dictionary<string, T>();
AsyncList = new List<T>();
Factory = factory;
}
public override T Get(string name)
{
if (!Pairs.ContainsKey(name))
{
2019-12-16 14:55:59 +00:00
Pairs.Add(name, base.Get(name));
2019-11-29 12:26:53 +00:00
}
2019-12-16 14:55:59 +00:00
return Pairs[name];
2019-11-29 12:26:53 +00:00
}
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
2019-12-16 14:55:59 +00:00
public class DbContextManager<T> : BaseDbContextManager<T> where T : BaseDbContext, new()
{
public DbContextManager(IOptionsFactory<T> factory) : base(factory)
{
}
}
public class MultiRegionalDbContextManager<T> : BaseDbContextManager<MultiRegionalDbContext<T>> where T : BaseDbContext, new()
{
public MultiRegionalDbContextManager(IOptionsFactory<MultiRegionalDbContext<T>> factory) : base(factory)
{
}
}
2019-12-10 15:06:51 +00:00
public static class DbContextManagerExtension
{
2020-02-17 08:58:14 +00:00
public static DIHelper AddDbContextManagerService<T>(this DIHelper services) where T : BaseDbContext, new()
2019-12-10 15:06:51 +00:00
{
2020-07-17 10:52:28 +00:00
if (services.TryAddScoped<DbContextManager<T>>())
{
services.TryAddScoped<MultiRegionalDbContextManager<T>>();
services.TryAddScoped<IConfigureOptions<T>, ConfigureDbContext>();
services.TryAddScoped<IConfigureOptions<MultiRegionalDbContext<T>>, ConfigureMultiRegionalDbContext<T>>();
2019-12-10 15:06:51 +00:00
2020-07-17 10:52:28 +00:00
return services.AddLoggerService();
}
return services;
2019-12-10 15:06:51 +00:00
}
}
2019-11-29 12:26:53 +00:00
}