Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would I want to use UnitOfWork with Repository Pattern?

I've seen a lot about UnitOfWork and Repo Pattern on the web but still don't have a clear understanding of why and when to use -- its somewhat confusing to me.

Considering I can make my repositories testable by using DI thru the use of an IoC as suggested in this post What are best practices for managing DataContext. I'm considering passing in a context as a dependency on my repository constructor then disposing of it like so?:

public interface ICustomObjectContext : IDisposable {}
public IRepository<T> // Not sure if I need to reference IDisposable here
public IMyRepository : IRepository<MyRepository> {}

public class MyRepository : IMyRepository
{
    private readonly ICustomObjectContext _customObjectContext;

    public MyRepository(ICustomObjectContext customObjectContext)
    {
        _customObjectContext = customObjectContext;
    }

    public void Dispose()
    {
        if (_customObjectContext != null)
        {
            _customObjectContext.Dispose();
        }
    }

    ...

}

My current understanding of using UnitOfWork with Repository Pattern, is to perform an operation across multiple repositories -- this behavior seems to contradict what @Ladislav Mrnka recommends for web applications:

For web applications use single context per request. For web services use single context per call. In WinForms or WPF application use single context per form or per presenter. There can be some special requirements which will not allow to use this approach but in most situation this is enough.

See the full answer here

If I understand him correctly the DataContext should be shortlived and used on a per request or presenter basis (seen this in other posts as well). In this case it would be appropriate for the repo to perform operations against the context since the scope is limited to the component using it -- right?

My repos are registered in the IoC as transient, so I should get a new one with each request. If that's correct, then I should be getting a new context (with code above) with each request as well and then disposing of it -- that said...Why would I use the UnitOfWork Pattern with the Repository Pattern if I'm following the convention above?

like image 633
Rich Avatar asked Dec 22 '22 04:12

Rich


1 Answers

As far as I understand the Unit of Work pattern doesn't necessarily cover multiple contexts. It just encapsulates a single operation or -- well -- unit of work, similar to a transaction.

Creating your context basically starts a Unit of Work; calling DbContext.SaveChanges() finishes it.

I'd even go so far as to say that in its current implementation Entity Framework's DbContext / ObjectContext resembles both the repository pattern and the unit of work pattern.

like image 126
Dennis Traub Avatar answered Dec 29 '22 10:12

Dennis Traub