Andrew Simpson
Andrew Simpson

Reputation: 7324

How to pass ILogger to my filter

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..

Upvotes: 9

Views: 3667

Answers (1)

Josh Stevens
Josh Stevens

Reputation: 4221

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));
});

Upvotes: 11

Related Questions