Skip to content

Instantly share code, notes, and snippets.

@benmccallum
Last active November 12, 2020 15:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benmccallum/8759f84b03220de781d9f13fd11b715a to your computer and use it in GitHub Desktop.
Save benmccallum/8759f84b03220de781d9f13fd11b715a to your computer and use it in GitHub Desktop.
Abstraction around EF Core 3 DbContextPool
// In your Startup.cs
.AddSingleton<IDbContextPool<MyCompanyDbContext>, OurDbContextPool<MyCompanyDbContext>>()

// In consumer code:
await using var db = _dbContextPool.Rent();
try
{
    await db.FindAsync(1);
}
finally
{
    _dbContextPool.Return(db);
}

#nullable enable
using Microsoft.EntityFrameworkCore;
namespace MyCompany
{
/// <summary>
/// An abstraction around EF Core's DbContextPool (as it's an internal API that becomes public in .NET 5)
/// for renting a DbContext.
/// </summary>
public interface IDbContextPool<TDbContext>
where TDbContext : DbContext
{
/// <summary>
/// Rents a DbContext from the pool.
/// When finished using, consumer should call <see cref="Return(TDbContext)"/>.
/// </summary>
/// <returns>Context.</returns>
TDbContext Rent();
/// <summary>
/// Returns a DbContext to the pool.
/// </summary>
/// <param name="context">Context to return.</param>
/// <returns></returns>
bool Return(TDbContext context);
}
}
#nullable enable
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Internal;
namespace MyCompany
{
#pragma warning disable EF1001 // Internal EF Core API usage.
/// <inheritdoc/>
public class OurDbContextPool<TDbContext> : IDbContextPool<TDbContext>
where TDbContext : DbContext
{
private readonly DbContextPool<TDbContext> _dbContextPool;
public OurDbContextPool(DbContextPool<TDbContext> dbContextPool) => _dbContextPool = dbContextPool;
/// <inheritdoc/>
public TDbContext Rent() => _dbContextPool.Rent();
/// <inheritdoc/>
public bool Return(TDbContext context) => _dbContextPool.Return(context);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment