Home > Software engineering >  using DbContext in a manually created scope in a singleton service results in ObjectDisposedExceptio
using DbContext in a manually created scope in a singleton service results in ObjectDisposedExceptio

Time:08-30

Note: In the hour I spent writing this post and in the process having a second and third look at everything, I found the solution to my problem. I decided to post this anyway, as I did not find the solution online and it might help others.

If you have any comments about my architecture, please do share them! My guts tell me I should not have stumbled across this problem in the first place, but I can't point my finger to a specific detail.


In my .NET 6 application I have a service which needs to access the database, thus use a DbContext. The service is registered as singleton, but the DbContext is not, as it should be. Quite a number of similar questions out there are answered with inject IServiceScopeFactory and create (and dispose) your scope for each operation. example 1, example 2, example from Microsoft.

I try to do exactly that, but it throws ObjectDisposedExceptions, so it obviously does not work in my case. The question is: why?

The service(s) I'm talking about are data access services for the rest of the application, the gateway to the database. They are registered as singletons, because they fire events consumed by background services for certain actions.

I moved the context and scope handling into an abstract class, that looks like this (stripped down):

(I obviously renamed all classes, I'm not working on a cat related application, if something does not add up, I might have forgotten to remane something

  • Related