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)?
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 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.
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.
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.
It's quite OK, but once you feel that the Controller becomes too cluttered, you can refactor its dependencies to an Aggregate Service.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With