C
C#6mo ago
MC_2018

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?
using var context = Program.ServiceProvider.GetRequiredService<ShuffullContext>();
using var context = Program.ServiceProvider.GetRequiredService<ShuffullContext>();
Or does the IServiceProvider handle disposal and no longer require it?
var context = Program.ServiceProvider.GetRequiredService<ShuffullContext>();
var context = Program.ServiceProvider.GetRequiredService<ShuffullContext>();
2 Replies
MC_2018
MC_20186mo ago
An answer was provided by jbottom42, and the answer is that they should still be disposed by the user with using.
Artis Vilciņš
Artis Vilciņš6mo ago
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.