Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is Entity Framework Core with Dependency Injection disposed?

In Entity Framework Core you would normally use something like this, which should work in pretty much all cases:

using (var dbContext = new MyDbContext()) {
    await dbContext.Entities.WhereAsync(e => e.Something == somethingElse);
    await dbContext.SaveChangesAsync();
}

You can also use Dependency Injection with the database context. Now you would add the database context to the DI container and inject this into the classes/controllers/constructors/methods where you need it:

IHostBuilder builder = new HostBuilder()
    .ConfigureServices((context, collection) => {
        string connectionString = context.Configuration.GetConnectionString("MyDatabase");
        collection.AddDbContext<MyDbContext>();

...

public class Foo {
    public Foo(MyDbContext dbContext) { }
}

However, injecting this into a class/constructor you would usually keep the instance as a local variable, which is fair enough, but there's no longer any possibility to use the using statements. Now two different methods could end up using the same dbContext at the same time which will most likely cause concurrency issues.

If the dbContext was not injected but just used in a using statement then there should be no problem with concurrency and the object would be disposed at the end of each method.

So how would you correctly handle concurrency and disposing with Entity Framework Core and Dependency Injection?

like image 480
GTHvidsten Avatar asked Dec 07 '25 08:12

GTHvidsten


1 Answers

By default the extension methods AddDbContext do:

services.AddScoped<MyDbContext>()

So in case of AddDbContext, a new instance will be created for each request and would get disposed once the work is done (objects are the same within a request, but different across different requests). So, you shouldn't have any problem with concurrency here.

Also you can add context to DI as transient if you need a new instance for every controller and every service.

like image 140
Pr.Dumbledor Avatar answered Dec 08 '25 21:12

Pr.Dumbledor