Correct implementation of UnitOfWork and Repository pattern in Entity Framework

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

Question

I'm attempting to use Entity Framework's UoW and Repository pattern in the right way. Despite the many posts opposing it, I still believe that it is the best course of action.

I'm attempting to follow this blog entry. The Repositories need to be injected into the UoW, but in a manner that allows me to do it whenever I need to. That is the final thing I'm attempting to figure out. The function Object() { [native code] } may expand as the number of repositories does. Furthermore, it seems like a waste of resources to instantiate all the repositories for an activity that could only need 1 or 2.

How can I do this in a manner that makes it simple for me to create unit tests?

Only by doing it in the getter, I was able to inject repositories NOT in the function Object() { [native code] } (so they are not all created, even when they are not required for a certain operation):

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);
    }
}

This method, however, causes a lot of noise in the code since I will require 50 props when I have 50 repositories.

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

Popular Answer

The suggested strategy, which I appreciate, may be used with the generic repository approach mentioned in https://cpratt.co/truly-generic-repository/. If the UoW pattern from the blog post you mention is implemented correctly, you won't need anything more than the IReadOnlyRepository from the article since it already comes with everything the repository needs to function.

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