R – How you design Controller layer of MVC design pattern in .NET


Here are my thoughts: The purpose of using MVC is seperation of concerns and testability of gui logic. View should be able to work with different models and model should be able to work with different views.

I think controller class must implement an interface for mocking/testing reasons and view should call controller methods through this interface. But if we do so, then it becomes difficult to process view elements (textboxes, grids etc.) in controller. So these elements must be known by the controller somehow.

1. Do you expose these gui elements through the interface? Define controller classes as partial classes so that controller can directly process the gui elements (what about the interface then)? What do you do to solve this problem?

2. Basically, should controller implement more than one interface? One for view and another for model layer, to make view/model be able to work with different models/views via controllers?

3. Model layer also should implement an interface for mocking/testing?

How can we achieve our testing, loosely coupling, SoC purposes best? Please share your experience/thoughts.

Best Solution

I believe the view should implement an interface and be passed into the controller, usually through the constructor. This way a controller could use the fields of the view interface to get at the values of the controls the view uses. It could also use any model of your choosing. This would give you the loose coupling between the model and view that you want.

The same could be done for the model by passing a repository for your model in through the constructor. The repository methods could then return interfaces that your model classes must implement.

You could then have the controllers implement an interface and get the appropriate controller at run time using an IoC container (which would automatically supply the controller with the appropriate view and model repository. That would make your controllers able to be swapped out easily to replace the current view/model combination for a different one. In general, however, I find this to be unecessary because I only ever have one controller for each type of view (view interface).