NET 5 和 EF:如何在服务中使用 AddPooledDbContextFactory 代替 DbContext

Aes*_*eir 10 c# entity-framework entity-framework-core asp.net-core .net-5

AddPooledDbContextFactory我最近在 NET 5 自学文章中发现了这个概念,并热衷于正确实施它。但是,我不确定如何将它与我通常使用的泛型一起使用。

我当前的设置示例:

public void ConfigureServices(IServiceCollection services)
   {
        services.AddDbContext<TestDbContext>(
                (s, o) => o.UseNpgsql(Configuration.GetConnectionString("DatabaseConnection"))
                           .UseLoggerFactory(s.GetRequiredService<ILoggerFactory>()));

// other code //
    }
Run Code Online (Sandbox Code Playgroud)

我的存储库通用:

    public class Repository<T> : IRepository<T> where T
    {
        private readonly TestDbContext _dbContext;
        public Repository(TestDbContext dbContext)
        {
            _dbContext = dbContext;
        }
        

        public async Task Create(T entity)
        {
           await _dbContext.Set<T>().AddAsync(entity);
           await _dbContext.SaveChangesAsync();
        }

        // other methods //
   }
Run Code Online (Sandbox Code Playgroud)

作为示例,这是通过以下方式调用的:

public class WeatherForecastController : ControllerBase
{
    
    private readonly IRepository<Test> testRepo;

    public WeatherForecastController(IRepository<Test> testRepo)
    {
        this.testRepo= testRepo;
    }

    [HttpGet]
    public async Task<IEnumerable<WeatherForecast>> GetAsync()
    {
        await testRepo.Create(new Test { Name = "Superman" });
        
        // other code
    }

}
Run Code Online (Sandbox Code Playgroud)

我想将其转换为使用新的 AddPooledDbContextFactory 概念,但找不到足够的文档来弄清楚如何执行此操作。

Atm 唯一想到的是在每个方法中使用语句,但这没有意义。

对此有什么建议吗?

Moh*_*our 4

文档尚未完成,正在进行中,您跟踪此问题 https://github.com/dotnet/EntityFramework.Docs/issues/2523

您还可以查看测试,AddPooledDbContextFactory了解如何DbContext注册 https://github.com/dotnet/efcore/search?q=AddPooledDbContextFactory

例如注册 DbContext:

services.AddPooledDbContextFactory<TContext>(ob =>
    ob.UseSqlServer("ConnectionString").EnableServiceProviderCaching(false), poolSize: 32)
Run Code Online (Sandbox Code Playgroud)

然后在你的类中,注入IDbContextFactory<TContext>并使用它,如下所示:

services.AddPooledDbContextFactory<TContext>(ob =>
    ob.UseSqlServer("ConnectionString").EnableServiceProviderCaching(false), poolSize: 32)
Run Code Online (Sandbox Code Playgroud)

根据这篇文章

请注意,以这种方式创建的 DbContext 实例不由应用程序的服务提供者管理,因此必须由应用程序处置

您还可以查看这篇文章以了解如何使用IDbContextFactoryhttps://learn.microsoft.com/en-us/aspnet/core/blazor/blazor-server-ef-core ?view=aspnetcore-5.0