简体   繁体   中英

Correct implementation of UnitOfWork and Repository pattern in Entity Framework

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.

您可能希望将描述的方法(我喜欢)与此处描述的通用存储库方法结合使用https://cpratt.co/truly-generic-repository/鉴于您所引用的博客文章中的UoW模式得到了适当的实现,您将赢得除了文章中的IReadOnlyRepository之外,不需要任何其他内容-它会为您提供存储库所需的一切。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM