Search code examples
asp.net-mvcdependency-injectioncontrolleractionmethod

Dependency Injection into an MVC action method


I'm wondering if this is possible. I have a typical MVC action method with a signature that looks like this:

public ActionResult View(MyModel model)
{
   IAnObject myObject = new AnObject();
   //several lines of code follow.....
   return View(model);
}

I'd like to get rid of that new keyword and inject an instance of IAnObject into the action method. But I'm not sure if MVC allows for this, injecting a class along side a model in an action method? Has anyone run across this, and are there ways of tackling it? (Our IoC container is Windsor, in case that makes a difference.)


Solution

  • If you are expecting to inject this reference into the action method as a parameter, you can look to the ControllerActionInvoker, which has an InvokeActionMethod method, which I believe is called from InvokeAction. This method has a list of parameters passed into it, and a description of the action (ActionDescriptor class). This action descriptor has a GetParameters method that will give you more detailed information about the parameter, such as type information that you would need for the dependency injector. I've not done this, so I don't know quite how it works out, but it seems possible.

    I also don't know how that might affect how MVC selects an action method to post to, so factor that in.