I have an ASP.NET MVC 3 application and I use Ninject to inject dependencies into my classes.
Actions on controllers pass ViewModels (which do not contain logic) to the presentation layer.
When the HTTP POSTED MVC 3 form creates an instance of the ViewModel and associates the incoming POST data with the ViewModel properties. MVC 3 uses the DefaultModelBinder class to instantiate and bind.
Most of my ViewModels models use a dependency that I really don't want to install from each individual controller method (DRY principle).
Therefore, I created an individual subclass of DefaultModelBinder as follows:
using System; using System.Web.Mvc; namespace Application.Classes { public sealed class CustomModelBinder : DefaultModelBinder { private readonly IDependencyResolver DependencyResolver; public CustomModelBinder( IDependencyResolver dependencyResolver ) { DependencyResolver = dependencyResolver; } protected override object CreateModel( ControllerContext controllerContext , ModelBindingContext modelBindingContext , Type modelType ) { return DependencyResolver.GetService( modelType ); } } }
And I installed it to replace DefaultModelBinder as follows (in Global.asax.cs):
protected void Application_Start() {
By doing this, when the Controller method gets a ViewModel, it will be the one that Ninject created using the I binding specified in my NinjectModule. ViewModel now gets the dependencies nested in the constructor.
Is this a suitable use of a locator service template?
clarifications / UPDATE:
source share