Home > Software design >  What is the difference between AddDbContextPool and AddDbContextFactory?
What is the difference between AddDbContextPool and AddDbContextFactory?

Time:09-14

Here are the codes in .NET 6 in program.cs

builder.Services.AddDbContextPool<MyDbContext>(options =>
{
    options.UseSqlServer(connstr);
});

builder.Services.AddDbContextFactory<MyDbContext>(options =>
{
    options.UseSqlServer(connstr);
});

What is the difference between AddDbContextPool and AddDbContextFactory? What are the pro and cons of it?

CodePudding user response:

From a consumer's standpoint, there's not much difference between AddDbContext and AddDbContextPool. In both cases, you get a scoped instance of a MyDbContext from the DI. With the pooling option, the Context gets reset rather than disposed which saves resources during the instantiation.

AddDbContextFactory gives you the ability to create and manage DbContext instances yourself:

using (var context = _contextFactory.CreateDbContext())
{
    // ...
}

That's useful when you don't have an explicit Unit of Work (e.g. request) or you want to keep the Context instance short-lived (during an intensive data pipeline task, as too many operations against the same instance can get very slow).

  • Related