Singleton service creating an object that requires a scoped service

David Thielen 3,211 Reputation points
2023-10-13T01:49:01.1033333+00:00

Hi all;

I'm getting a scope error on this:

I use AddDbContextFactory() to get a factory that I then use to get a DbContext. The factory is singleton scoped.

The DbContext constructor requires a service. The required service has session scope (it must). The factory is creating this DbContext.

The DbContext created will have a very short lifespan, and be disposed before the session ends. But the factory does not know that.

In this case, is this a scope exception? That the singleton factory will not allow the DbContext it creates to have a session scoped service in its constructor?

And if so, is there any way around this? I think I can make the DbContextFactory session scoped - but is that a good idea?

Is there a way to load the service other than as a constructor parameter?

The way my code is written, the created DbContext will always have a lifespan within the session scope.

thanks - dave

Developer technologies .NET Blazor
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.