C# EF core Connection Pooling

Date: 2019-06-18
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore.Internal;

namespace EfDataAdapter
{
    public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
    {
        public static DbContextOptions Options = GetOptions();

        static ApplicationDbContextFactory() { 
            DbContextPool = new DbContextPool<ApplicationDbContext>(GetOptions());
        }

        private static DbContextPool<ApplicationDbContext> DbContextPool { get; }
        public static DbContextOptions GetOptions()
        {
            var assemblyName = typeof(ApplicationDbContextFactory).Assembly.GetName().Name;
            var settings = new EfSettings();
            var connectionString = settings.ConnectionString;
            var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
            optionsBuilder.UseSqlServer(connectionString, b => b.MigrationsAssembly(assemblyName));
            return optionsBuilder.Options;
        }
        
        public ApplicationDbContext CreateDbContext(string[] args)
        {
            return DbContextPool.Rent();
        }
        public void ReturnDbContext(ApplicationDbContext applicationDbContext)
        {
            DbContextPool.Return(applicationDbContext);
        }
    }
}
using System;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace EfDataAdapter.UnitOfWork
{
    public class UnitOfWork : IUnitOfWork, IDisposable
    {
        private ApplicationDbContext _dbContext { get; set; }
        private ApplicationDbContextFactory _dbContextFactory;
        public UnitOfWork(DbContext context)
        {
            _dbContextFactory = new ApplicationDbContextFactory();
            _dbContext = (ApplicationDbContext)context;
        }
        public UnitOfWork()
        {
            _dbContextFactory = new ApplicationDbContextFactory();
            CreateDbContext();
        }
        private void CreateDbContext()
        {
            _dbContext = _dbContextFactory.GetDbContext();
        }
        public void Commit()
        {
            _dbContext.SaveChanges();
        }
        public async Task<int> CommitAsync()
        {
            return await _dbContext.SaveChangesAsync();
        }
        public DbContext GetContext()
        {
            return _dbContext;
        }
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_dbContext != null)
                {
                    //_dbContext.Dispose();
                    _dbContextFactory.ReturnDbContext(_dbContext);
                }
            }
        }
    }
}
22110cookie-checkC# EF core Connection Pooling