Dale Fraser
Dale Fraser

Reputation: 4758

When does a DbContext instance get disposed in ASP.NET Core 5

I'm using the recommended approach to create DbContext instance through dependency injection.

In Startup.cs -

services.AddDbContext<DashboardContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DashboardConnection")));

and in the Controller -

private readonly DashboardContext db;
public AccountController(DashboardContext context)
{
    db = context;
}

What I want to know is when this instance gets disposed.

Previously we would always use the using statement which would dispose on close of braces -

using (DashboardContext db = new DashboardContext())
{
    // Query
}

Upvotes: 4

Views: 4408

Answers (1)

atiyar
atiyar

Reputation: 8305

With the AddDbContext method, a DbContext will be created with Scoped lifetime by default; which means, it's lifetime is scoped within the current request, and it will get disposed as soon as the current request completes.

But you can override the default by passing a value for the contextLifetime parameter, like -

services.AddDbContext<DashboardContext>(options => 
    options.UseSqlServer(
        Configuration.GetConnectionString("DashboardConnection")),
        ServiceLifetime.Transient);

For further detail check - AddDbContext

EDIT - (in reply to @Dale's comment) :
Considering the overall architecture of the ASP.NET Core MVC, and how we tend to use the framework, I'd say (personal opinion) that in general for most applications its better to stick to the default Scoped lifetime.
In the answer, I just wanted to make it clear that the option for manual config is there for you. Of course, there might be use cases or scenarios (depending on how you design your own application) where the manual config has its use.

Upvotes: 7

Related Questions