Correct implementation of UnitOfWork and Repository pattern in Entity Framework

asp.net-mvc c# entity-framework entity-framework-6

Question

I am trying to figure out how to correctly implement UoW and Repository pattern with Entity Framework. I saw a lot of post against it but it still seems like the right way to go.

I am trying to do it according to this blog post. The last thing I am trying to figure out is how to inject the Repositories into the UoW but in a way that lets me do it on demand. The number of repositories may grow and so will the constructor then. Furthermore instantiating all of the repositories for an operation that may require only 1 or 2 seems like a waste of resources.

How do I do it in a way that lets me write unit tests fairly easily?

The only way I found out, that lets me inject repositories NOT in the constructor (so they are not all instantiated, even when they are not needed for a particular operation) is by doing it in the getter:

private IGenericRepository<Blog> _blogRepository;
private IGenericRepository<Post> _postRepository;
public UnitOfWork(BloggingContext bloggingContext)
{
    _bloggingContext = bloggingContext;
}

public IGenericRepository<Blog> BlogRepository
{
    get
    {
        return _blogRepository = _blogRepository ?? new GenericRepository<Blog>(_bloggingContext);
    }
}

However, this approach generates a lot of noise in the code because when I will have 50 repositories I will need 50 props.

1
1
4/22/2018 11:24:47 AM

Popular Answer

You might want to combine the described approach (which I like) with the generic repository approach described here https://cpratt.co/truly-generic-repository/ Given proper implementation of the UoW pattern from the blog post you reference, you won't need the anything but the IReadOnlyRepository from the article - it will provide everything you need for the repository to be.

0
10/1/2018 11:17:04 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow