mardi 22 août 2023

Using scoped services (ie DbContext) from two scopes without service locator

I need to write some service with method that needs to perform two units of work, where second one will be preformed even if first failed and was rolled back. Creating and rolling back transaction is not enough, because DbContext still remembers changes from first unit of work. Therefore I need two DbContexts. Because I use other services to perform the work itself, I need to get the DbContext to them and i want it to be injected, not manually created or obtained via service locator.

Usual approach is to inject IServiceScopeFactory, create scope and from it resolve services involved in the work (DbContext to manage transaction and some service to do the work using this DbContext). What I don't like about this, is that nowhere in signature of the containing service or it's methods is information that those services are needed, and that my service knows about IServiceScopeFactory therefore knows at least something about used DI framework.

I'd like solution that allows my services to know as little as possible about DI framwork (it is allowed to know that conceptually scopes exist, but should not depend on any class/interface from DI framework).

Aucun commentaire:

Enregistrer un commentaire