Where is the recommended place to perform property injection into action filter attributes in an ASP.NET web api project? In MVC 3 land, we could set our own implementation for ControllerActionInvoker at the point of resolving our controllers from our IoC container, and override its GetFilters() method to inject components resolved from the container.
Is there a similar place to do this in an ASP.NET Web API project? I have a controller factory that resolves controllers from the container, with the CreateController method as so:
public IHttpController CreateController(HttpControllerContext controllerContext, string controllerName)
{
var controller = _kernel.Resolve<IHttpController>(controllerName);
controllerContext.Controller = controller;
controllerContext.ControllerDescriptor = new HttpControllerDescriptor(_configuration, controllerName, controller.GetType());
return controllerContext.Controller;
}
I’ve had a look at HttpControllerDescriptor to see if there is somewhere to do the injection, but I can’t see a suitable place. Any pointers in the right direction?
You need to implement
IHttpControllerSelectorand register your selector in the (Servicesproperty)DefaultServicesof theHttpConfiguration.Or alternatively, to use your own resolver/DI framework, you need to replace the resolver. See here for an example.
You need to Implement your own
IFilterProvider. Have a look at the source forActionDescriptorFilterProvider. This is where you can inject properties.Here is
ActionDescriptorFilterProviderimplementation:All you have to do is to use
instancelambda parameter and inject properties.Registration As you have figured out, the filter provider needs to be registered against the
HttpConfiguration. Or alternatively, to use your own resolver/DI framework, you need to replace the resolver. See here for an example.