Where is it best to load secondary datasets in MVC?
Say I have a class Student and a Student has a Tutor. On my edit student page I want to display a list of Tutors to pick from.
To do this I will at some point need to hit the Student repository to get the current student and the tutor repository to get a list of all tutors. I'm using Dependency Injection to get my repo instances.
I have a view model class which the controller populates before passing to the view for rendering. I have given that class an IEnumerable<Tutor>
which I can use in the view to render a dropdown.
My question: who should populate the list of tutors?
Should the controller be responsible for loading all data, or, should I get the view model class to load 开发者_如何学运维it? I can't decide who's concern this is.
Either way, in a more complicated scenario where there are multiple secondary datasets, one of the classes is going to end up with a contstructor being injected with lots or repositories.
It would definitely be the role of the controller as you don't want your viewmodel to be bound to always loading that particular list of tutors.
The interesting problem is, as you said, avoiding having several IRepository instances injected into the constructor and it's a problem with the repository pattern as a whole and some people have gone as far as to suggest the repository pattern is dead.
I don't know if that is the case, but what I would suggest is that you carefully think about how you structure your data access objects so that you avoid situations where you are blindly injecting repositories around, because that can be very detrimental.
What I tend to do is use the IRepository<>
instances as a basis for constructing another repository which has a much closer representation to how my application is accessing data.
I usually let the controller worry about populating separate parts of the view model before sending it to the view. There are times when you might use the same view model in multiple places, and not necessarily still want to populate all its fields (in this case, IEnumerable<Tutor>
)
I think it makes sense - the controller's responsibility can then be viewed as:
- getting the data from somewhere else (repository) and packaging it together as the viewmodel
- passing the viewmodel to the view
精彩评论