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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With