I have an ASP.NET MVC 3 application and am using Ninject for injecting dependencies into my classes.
Actions on the Controllers pass ViewModels (that do not contain logic) to the view layer.
When a HTTP form is POSTed MVC 3 creates a ViewModel instance and binds the incoming POST data to the ViewModel's properties. MVC 3 uses a class called DefaultModelBinder to create the instance and perform the binding.
Most of my ViewModels share a dependency which I do not really want to set from each individual Controller method (DRY principle).
Therefore, I have created a customized 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 have set it to replace the DefaultModelBinder as follows (in Global.asax.cs):
protected void Application_Start() {
// ...
ModelBinders.Binders.DefaultBinder = new CustomModelBinder( DependencyResolver.Current );
// ...
}
By doing this when a Controller method receives a ViewModel, it will be one that was built by Ninject using the binding I sepecified in my NinjectModule. The ViewModel now receives it's dependencies injected into it's constructor.
Is this an appropriate use of the Service Locator Pattern?
CLARIFICATION/UPDATES:
- The application uses Ninject and is integrated into the MVC system as documented on the Ninject Wiki (https://github.com/ninject/ninject.web.mvc/wiki/Setting-up-an-MVC3-application)