Search code examples
c#asp.net-mvc-3castle-windsoraction-filter

Resolving dependencies in global actionfilters?


I have inherited from and extended the HandleErrorAttribute of MVC3 with some custom logging.

One thing I am struggling to do though is to neatly resolve a dependency in it using Castle Windsor.

Generally I resolve these sorts of dependencies in an extension of the ControllerActionInvoker, but it seems that the HandleErrorAttribute does not pass through here.

Where is it invoked from that I can hook in and extend it?

Thanks.

As an example of what I currently do: https://stackoverflow.com/a/6627002/148998


Solution

  • What I ended up doing was extending the ControllerActionInvoker and resolving any attribute dependencies there, specifically for the exception filters.

    The code:

      public class WindsorActionInvoker : ControllerActionInvoker
        {
            private readonly IKernel _kernel;
    
            public WindsorActionInvoker(IKernel kernel)
            {
                _kernel = kernel;
            }
    
            protected override ExceptionContext InvokeExceptionFilters(ControllerContext controllerContext, IList<IExceptionFilter> filters, System.Exception exception)
            {
                foreach (var actionFilter in filters.Where(actionFilter => !(actionFilter.GetType() == controllerContext.Controller.GetType())))
                {
                    _kernel.InjectProperties(actionFilter);
                }
    
                return base.InvokeExceptionFilters(controllerContext, filters, exception);
            }