variable
variable

Reputation: 9684

What is the alternative to unit of work pattern when using generic repository pattern to handle transactions?

I know dbcontext is inherently a repository and unit of work pattern.

However as an abstraction suppose I implement a generic repository pattern, with unit of work pattern, then this can handle situation wherein suppose author and book are inserted and one of them fails then neither will be inserted.

Now suppose I don't use the unit of work pattern then what is the alternate approach to handle transaction behaviour when using the generic repository pattern?

Upvotes: 1

Views: 1217

Answers (1)

sarvasana
sarvasana

Reputation: 757

You could use a transaction scope outside your repositories.
If your code never reaches the call to Complete() and the scope is disposed, the transaction is aborted and a rollback will occur.

using var scope = new TransactionScope(
    TransactionScopeOption.Required, 
    new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted },  
    TransactionScopeAsyncFlowOption.Enabled);

authorRepository.Add(author);
bookRepository.Add(book);

scope.Complete();

But why not inject a request scoped UnitOfWork into each of your repositories and have that wrap and handle the transactions for you?

Upvotes: 1

Related Questions