Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between AddDbContextPool and AddDbContextFactory?

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?

like image 784
Steve Avatar asked Jan 21 '26 20:01

Steve


1 Answers

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).

like image 179
hkarask Avatar answered Jan 23 '26 09:01

hkarask



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!