Property Injection into Web API's `System.Web.Http.Filters.ActionFilterAttribute`

asp.net-web-api

Solution

You need to implement `IHttpControllerSelector` and register your selector in the (`Services` property) `DefaultServices` of the `HttpConfiguration`.

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 for `ActionDescriptorFilterProvider`. This is where you can inject properties.

Here is `ActionDescriptorFilterProvider` implementation:

    public IEnumerable<FilterInfo> GetFilters(HttpConfiguration configuration, HttpActionDescriptor actionDescriptor)
    {
        if (configuration == null)
        {
            throw Error.ArgumentNull("configuration");
        }

        if (actionDescriptor == null)
        {
            throw Error.ArgumentNull("actionDescriptor");
        }

        IEnumerable<FilterInfo> controllerFilters = actionDescriptor.ControllerDescriptor.GetFilters().Select(instance => new FilterInfo(instance, FilterScope.Controller));
        IEnumerable<FilterInfo> actionFilters = actionDescriptor.GetFilters().Select(instance => new FilterInfo(instance, FilterScope.Action));

        return controllerFilters.Concat(actionFilters);
    }

All you have to do is to use `instance` lambda 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.

Problem

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?

Original source