DbContextScope ReadOnly and Create Context in same service

684 Views Asked by At

Is there a pattern which allows for a Service class to handle both read and write operations? Im trying to retrofit our current service layer to use DbContextScope github/mehdime/DbContextScope (no repo layer) and we do read/write operations in the same class.

If I use a single IDbContextScopeFactory object, it will throw an exception Cannot nest a read/write DbContextScope within a read-only DbContextScope

I dont want to have to create two service classes, just to handle read or write operations, is there away around this? If its solely a scoping issue, perhaps i can somehow design the layer in a way that will have separate scopes for each operation type?

Any guidance would be very helpfull!

1

There are 1 best solutions below

0
On

I found why the exception was being thrown. I was trying to create a dbContext instance in the same line where i was referencing the factory call.

using (var db = _dbContextScopeFactory.Create().DBContexts.Get<*NAME*>()) {}

I think this was causing the the dbContext be disposed incorrectly. Once i refactored the code to retrieve the dbContext outside of the using line, the errors stopped.

using (var fact = _dbContextScopeFactory.Create()) { var db = fact.DbContexts.Get<*NAME*>(); }