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..
You should add your filter using
Add<T>, this allows us to resolve the filter from the IoC container. This means yourILogWriterwill be injected in for you on use of the filter.On top of this as Nkosi comment says you can use
typeofas well which will trigger the same behaviour as the above.