How should I manage Generic Repository Pattern when the works of different entities are pretty much different?

这一生的挚爱 提交于 2019-12-28 03:13:07

问题


I am new to Repository pattern.

When I am managing the CRUD operations of several entities (like: customers, orders etc) then its fine. I am making an interface, I am making a Generic repository. And that serves my purpose, because CRUD operation is common for them.

My question is:

When the duties of several entities are totally different, there is no common method between them, in this case what should I do? Should I increase the number of interfaces and repositories for those specific purposes? Or is there any better solution in terms of best practices?


回答1:


How should I manage Generic Repository Pattern when the works of different entities are pretty much different?

This is the core problem with Generic Repository pattern; that is why it is considered an anti-pattern.

I read this here:

No matter what clever mechanism I tried, I always ended up at the same problem: a repository is a part of the domain being modeled, and that domain is not generic. Not every entity can be deleted, not every entity can be added, not every entity has a repository. Queries vary wildly; the repository API becomes as unique as the entity itself.

Why generic repository is anti-pattern?

  1. A repository is a part of the domain being modeled, and that domain is not generic.
    • Not every entity can be deleted.
    • Not every entity can be added
    • Not every entity has a repository.
    • Queries vary wildly; the repository API becomes as unique as the entity itself.
    • For GetById(), identifier types may be different.
    • Updating specific fields (DML) not possible.
  2. Generic query mechanism is the responsibility of an ORM.
    • Most of the ORMs expose an implementation that closely resemble with Generic Repository.
    • Repositories should be implementing the SPECIFIC queries for entities by using the generic query mechanism exposed by ORM.
  3. Working with composite keys is not possible.
  4. It leaks DAL logic in Services anyway.
    • Predicate criteria if you accept as parameter needs to be provided from Service layer. If this is ORM specific class, it leaks ORM into Services.

I suggest you read these (1, 2, 3, 4, 5) articles explaining why generic repository is an anit-pattern.

Better approach is:

  1. Skip the Generic Repository. Implement concrete repositories.
  2. Use Generic Repository as abstract base repository. Derive all concrete repositories from it.

In any case, do not expose generic repository to calling code. Also, do not expose IQueryable from concrete repositories.



来源:https://stackoverflow.com/questions/49974181/how-should-i-manage-generic-repository-pattern-when-the-works-of-different-entit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!