How to use a DI / IoC container with the model binder in ASP.NET MVC 2+?

A couple of observations:

Don’t inject dependencies just to query them in the constructor

There’s no reason to inject an ITimeProvider into a user just to invoke Now immediately. Just inject the creation time directly instead:

public User(DateTime creationTime)
{
     this.CreationTime = creationTime;
}

A really good rule of thumb related to DI is that constructors should perform no logic.

Don’t use DI with ModelBinders

An ASP.NET MVC ModelBinder is a really poor place to do DI, particularly because you can’t use Constructor Injection. The only remaining option is the static Service Locator anti-pattern.

A ModelBinder translates HTTP GET and POST information to a strongly typed object, but conceptually these types aren’t domain objects, but similar to Data Transfer Objects.

A much better solution for ASP.NET MVC is to forego custom ModelBinders completely and instead explicitly embrace that what you receive from the HTTP connection is not your full domain object.

You can have a simple lookup or mapper to retrieve your domain object in your controller:

public ActionResult Create(UserPostModel userPost)
{
    User u = this.userRepository.Lookup(userPost);
    // ...
}

where this.userRepository is an injected dependency.

Leave a Comment