using Microsoft.Extensions.DependencyInjection; using Opsoft.NetCore.O3App.Domain; using Opsoft.NetCore.O3App.Shared; using Opsoft.NetCore.O3App.Shared.Data; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; namespace Opsoft.NetCore.O3App.Infrastructure.Repositories { [MapTo(typeof(IDapperContextFactory), ServiceLifetime.Scoped)] internal sealed class DapperContextFactory : IDapperContextFactory, IDisposable { private readonly IDbConnectionFactory dbConnectionFactory; private ConcurrentDictionary contexts = new ConcurrentDictionary(); private bool disposed = false; ~DapperContextFactory() { Dispose(false); } public DapperContextFactory(IDbConnectionFactory dbConnectionFactory) { this.dbConnectionFactory = Guard.ArgumentNotNull(dbConnectionFactory, nameof(dbConnectionFactory)); } public IDapperContext Create(string dbName = Constants.DatabaseNames.Default, bool @readonly = false) { if (disposed) { throw new ObjectDisposedException(nameof(DapperContextFactory), $"{nameof(DapperContextFactory)} is disposed"); } string key = $"{dbName}_{(@readonly ? "read" : "write")}"; DebugPrint($"Connection created: {key}"); if (!contexts.TryGetValue(key, out IDapperContext dapperContext)) { dapperContext = new DapperContext(dbConnectionFactory.GetConnection(dbName, @readonly)); contexts.AddOrUpdate(key, dapperContext, (oldKey, oldValue) => dapperContext); } return dapperContext; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (disposed) { return; } if (disposing) { if (contexts != null && contexts.Count > 0) { foreach (KeyValuePair context in contexts) { context.Value.Dispose(); } contexts.Clear(); contexts = null; } DebugPrint($"{nameof(DapperContextFactory)} disposed."); } disposed = true; } private void DebugPrint(string message) { #if DEBUG Console.WriteLine("{0:yyyy-MM-dd HH:mm:ss} [INFO] Thread {1}: {2}", DateTime.Now, Thread.CurrentThread.ManagedThreadId, message); #endif } } }