DbContext with IServiceProvider: whether or not to have a using statement
Hello, I have a straightforward question regarding using a DbContext from IServiceProvider. I'm aware that traditionally, when creating a DbContext, you should have a
using
statement; is this still needed when using the IServiceProvider?
Or does the IServiceProvider handle disposal and no longer require it?
2 Replies
An answer was provided by jbottom42, and the answer is that they should still be disposed by the user with
using
.I would leave that to service provider, but I would create a scope before using it and use it inside the operational scope and then discard of the scope. approximate example:
using var scope = Program.ServiceProvider.CreateScope();
var context = scope.ServiceProvider.GetRequiredService<ShuffullContext>();
// do some work using context and other services
I do not know if you have requirements for parallel working, but 1 context instance can not be used in parallel. That is the reason why context class should be scoped and created per usage true scoped context and not used inside root scope (as singleton).
When created scope is disposed it should dispose of correctly any classes it created, so you do not need add using when requiring context.