BestPractices: Is it acceptable to use more than one repository in a MVC-Controller?

爱⌒轻易说出口 提交于 2019-11-29 13:23:23

问题


I have a many-to-many assocition between an Employee and a Team. Foreach entity I have a repository.

Now I use ASP.NET MVC and I created a EmployeeController. I also created a View to edit an Employee. For this view I need a DropDownList with all Teams. The problem is that my EmployeeController only has got EmployeeRepository. So how can I get all Teams? My solution now is to use two repositories.

But is this a good solution?

Could I instead create TeamController and write a method returning all Teams (how would I do that)?


回答1:


Yes, it's perfectly acceptable for a controller to have references to two repositories.

In fact, my controllers work with multiple repositories more often than not.




回答2:


It's quite OK, but once you feel that the Controller becomes too cluttered, you can refactor its dependencies to an Aggregate Service.




回答3:


Wanna go smart? Do not use repositories inside controllers whatsoever. Instead use Domain Services. It doesn't sound so bad when you think one controller integrates the work of many services doesn't it?




回答4:


Typically you would create a repository for the aggregate root. The repository would have methods returning the entities populated for the controller.

If the entities are totally unrelated in your domain model you may want to create a service wrapping the two separate repositories to get the data you need.



来源:https://stackoverflow.com/questions/2329431/bestpractices-is-it-acceptable-to-use-more-than-one-repository-in-a-mvc-control

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