Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass ILogger to my filter

Tags:

I have an ASP.NET Web APi Service.

I have added a global error exception routine using IExceptionFilter.

To register the service I have this in my StartUp.cs:

services.AddMvc(options =>
{
    options.Filters.Add(new ErrorHandlingFilter()); 
});

My Exception Filter Class is this:

public class ErrorHandlingFilter : ApiControllerBase, IExceptionFilter
{
    public ErrorHandlingFilter(ILogWriter logger) : base(logger)
    {

    }


    public void OnException(ExceptionContext filterContext)
    {

        // If our exception has been handled, exit the function
        if (filterContext.ExceptionHandled)
        {
            return;
        }

        // Set our handled property to true
        filterContext.Result = new StatusCodeResult(500);
        filterContext.ExceptionHandled = true;
    }
}

But, obviously, I get a compile error at this line here:

 options.Filters.Add(new ErrorHandlingFilter()); 

because it is expecting me to pass an instance of ILogger.

But I define Ilogger here:

// Add singleton instance to the application for the LogWriter class
services.AddSingleton<ILogWriter, LogWriter>();

// Add singleton instance to the application for the NLog Logger which is used within the LogWriter implementation
services.AddSingleton(typeof(ILogger), LogManager.GetLogger("WebApi.Host"));

So, how can I pass an instance to my Exception Filter without duplication?

NB I admit this could be daft question, but it is very hot so brain is frazzled..

like image 609
Andrew Simpson Avatar asked Jul 19 '18 19:07

Andrew Simpson


1 Answers

You should add your filter using Add<T>, this allows us to resolve the filter from the IoC container. This means your ILogWriter will be injected in for you on use of the filter.

services.AddMvc(options =>
{
    options.Filters.Add<ErrorHandlingFilter>(); 
});

On top of this as Nkosi comment says you can use typeof as well which will trigger the same behaviour as the above.

services.AddMvc(options =>
{
  options.Filters.Add(typeof(ErrorHandlingFilter));
});
like image 151
Josh Stevens Avatar answered Sep 28 '22 17:09

Josh Stevens