How to use NInject (or other DI / IoC container) with the model binder in ASP.NET MVC 2 ?
Posted
by Andrei Rinea
on Stack Overflow
See other posts from Stack Overflow
or by Andrei Rinea
Published on 2010-05-24T19:30:12Z
Indexed on
2010/05/24
20:11 UTC
Read the original article
Hit count: 603
asp.net-mvc
|asp.net-mvc-2
|dependency-injection
|inversion-of-control
|modelbinders
Let's say I have an User entity and I would want to set it's CreationTime property in the constructor to DateTime.Now. But being a unit test adopter I don't want to access DateTime.Now directly but use an ITimeProvider :
public class User {
public User(ITimeProvider timeProvider) {
// ...
this.CreationTime = timeProvider.Now;
}
// .....
}
public interface ITimeProvider {
public DateTime Now { get; }
}
public class TimeProvider : ITimeProvider {
public DateTime Now { get { return DateTime.Now; } }
}
I am using NInject 2 in my ASP.NET MVC 2.0 application. I have a UserController and two Create methods (one for GET and one for POST). The one for GET is straight forward but the one for POST is not so straight and not so forward :P because I need to mess with the model binder to tell it to get a reference of an implementation of ITimeProvider in order to be able to construct an user instance.
public class UserController : Controller {
[HttpGet]
public ViewResult Create() {
return View();
}
[HttpPost]
public ActionResult Create(User user) {
// ...
}
}
I would also like to be able to keep all the features of the default model binder.
Any chance to solve this simple/elegant/etc? :D
© Stack Overflow or respective owner