// 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);
}
Last active
November 12, 2020 15:34
-
-
Save benmccallum/8759f84b03220de781d9f13fd11b715a to your computer and use it in GitHub Desktop.
Abstraction around EF Core 3 DbContextPool
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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