Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)?

like image 973
Rookian Avatar asked Feb 24 '10 20:02

Rookian


People also ask

What is the right way to include a repository into a controller?

By taking advantage of dependency injection (DI), repositories can be injected into a controller's constructor. the following diagram shows the relationship between the repository and Entity Framework data context, in which MVC controllers interact with the repository rather than directly with Entity Framework.

Why repository is used in MVC?

Why the repository pattern is used? The main purpose of the repository pattern is to isolate the data access layer and business logic.In Asp.Net MVC model is used to interact with the Data Access layer and Controller for performing Data access operation. The controller is responsible for passing data to the view.

Should controller access repository directly?

If you want to use repositories directly in controller, then you must write domain logics in the controller and it is not a good practice. Controllers have to be small and only forward requests to domain logic or services.

Why to use repository Pattern in c#?

The Repository pattern makes it easier to test your application logic. The Repository pattern allows you to easily test your application with unit tests. Remember that unit tests only test your code, not infrastructure, so the repository abstractions make it easier to achieve that goal.


1 Answers

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

like image 64
Mark Seemann Avatar answered Oct 13 '22 01:10

Mark Seemann