Вопрос

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.)

Это было полезно?

Решение

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.

Другие советы

You may want to do your injection in OnActionExecuting which is called before any action on the controller is executed. This will give you context such as the Request but will allow you to set member variables - thus 'simulating' constructor injection. And of course you only have to do it once for the whole controller.

    [NonAction]
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        _myService = .........;  // get from IoC container

        base.OnActionExecuting(filterContext);
    }

Well, I agree with the guys on the comments, but if you want to take an instance in the method scope, try to get it from your container of IoC, something like this:

public ActionResult View(MyModel model)
{
   // take from the container of IoC
   IAnObject myObject = _continerIoC.Resolve<IAnObject >();

   //several lines of code follow.....
   return View(model);
}

Avoid using the new to create your instance and your concrete type in the container and decouple your controller from dependecies/references.

I really consider using constructor/property Injection. There is a method injection too.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top