Dependency Injection in ExceptionFilterAttribute C#
Asked Answered
B

2

9

I am using Castle Windsor in my application and I would like to use inject some services example ILog in my ExceptionFilterAttribute :

public class GenericExceptionFilterAttribute : ExceptionFilterAttribute
{
    private readonly ILog _logger;

    public GenericExceptionFilterAttribute()            
    {

    }

    public GenericExceptionFilterAttribute(ILogManager logManager)
    {
        _logger = logManager.GetLogger(typeof(GenericExceptionFilterAttribute));
    }
}

How can I inject services in this class ?

Regards

Carlos

Blue answered 17/3, 2015 at 12:51 Comment(1)
Suggest you don't inject dependencies into attributes. Keep them passive.Tiffany
B
11

Hi the dependencyResolver to solve this :

 public override void OnException(HttpActionExecutedContext context)
                {
                    var log= (ILog)context.ActionContext.ControllerContext.Configuration.DependencyResolver.GetService(typeof(ILog));    
                }
Blue answered 17/3, 2015 at 13:46 Comment(1)
This worked for our project using SimpleInjector also, thank you! github.com/simpleinjector/SimpleInjectorSidman
S
0

Webapi has an interface called IFilterProvider that might support the kind of behavior you are looking for. Check https://mcmap.net/q/1315798/-webapi-filter-unity or http://michael-mckenna.com/blog/dependency-injection-for-asp-net-web-api-action-filters-in-3-easy-steps for examples on how to implement this. The second example is based on Unity but you can easily modify it to a Castle Windsor implementation. I've tried this solution a while back and it does provide a means to do proper constructor injection on action filters. As an alternative you might switch to Castle Windsor Interceptors. I tried this as well by creating an interceptor which did the exceptionhandling for me and registered it with Castle Windsor to intercept the controlles/actions I wanted. If you go one step further you can extend the interceptor to check the intercepted controller or action method for a custom attribute (which you can create yourself), and only do the exception handling if the attribute is there. This way, you can simply assign the interceptor to all controllers and manage the exceptionhandling on individual controllers/actions by applying the attribute if needed.

Silin answered 26/3, 2015 at 12:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.