I have a service layer, exposing methods to my MVC ‘layer’. Lets say I have a method that:
Public List<StateObjects> GetStates()
Is it good or poor design to then call that method, from the constructor of my Model object, to maybe build a SelectList of States, for my View? Should the Model have reference to my Service layer, and ALSO, allow my Controllers to have reference to my Service layer? Or should the population of the model’s variables be done in the controllers, so have all logic in the controller?
As you’ve pointed out there are 2 real options:
There is also a third option, which is to have the MC part of MVC in your domain layer. This makes it easier for model population but does blur the line a little a bit (if you are a purist) with what the business layer does. Practically, it doesn’t really matter until you’re building a giant enterprise model.
My particular preference is to have a static
public static MyModel FromDomainObject(DomainObject object)method on the models. You can then use this in your controller and pass in the domain object in the action to get a Model back, which you pass to your view.
The important part is to make sure the properties in the Model don’t populate on demand, and the methods aren’t accessible to the view. In reality you or the team will be calling these methods/properties and will know the implications, but it helps to keep the separation of concerns and decrease the coupling.