I’ve got an MVC controller that stores an object in Session. Different controller actions retrieve the object from Session, do stuff with it, and save it back.
I’d like to use Unity so that the controller just deals with an interface, but I’m not sure how to achieve this (I’m fairly new to the whole dependency injection thing). Here’s some sample code:
public class MyController : Controller
{
[HttpGet]
public ActionResult Index()
{
var state = new State();
// do stuff with state
Session[Key] = state;
return View();
}
[HttpPost]
public ActionResult Change()
{
var state = Session[Key] as State;
// do stuff with state
Session[Key] = state;
return View();
}
}
So basically I want to use IState instead of State. But where/how does Unity inject the concrete implementation? It seems like it can’t happen in the constructor, because I only need to instantiate a new object in the Index() action. Is there maybe some magic way I can add a parameter to Index() that Unity can use?
If you want to use Unity you must change your implementation little bit. You must define your controller as:
Now you need two additional step. You must use PerSessionLifetime manager for your
IStateresolving and you must configure Unity to resolve controllers and their dependencies – there is some build in support for resolving in ASP.NET MVC 3.Unity doesn’t provide PerSessionLifetime manager so you must build your own.
You can use this lifetime when configuring controller or you can configure extension in unity configuration and define your
IState: