I'm using Simple Injector in an ASP.NET Core 2.1 WebAPI application. I have an IExceptionFilter in which I want to log the error. My code is below (working), but is this the correct way? It looks like lot of work
public class HttpGlobalExceptionFilter : IExceptionFilter
{
private readonly ILogger logger;
public HttpGlobalExceptionFilter(Infrastructure.Common.ILogger logger)
{
// This is my own logger, implemented along the lines as mentioned here:
// https://stackoverflow.com/questions/41243485/
this.logger = logger;
}
public void OnException(ExceptionContext context)
{
// Irrelevant stuff
// ...
var error = $"An error occured: {context.Exception.Message}";
this.logger.LogError(error);
context.ExceptionHandled = true;
}
}
In my Startup.cs ConfigureServices(), I have:
services.AddMvc(options =>
{
options.Filters.Add(new SimpleInjectorExceptionFilterDispatcher(
this.container.GetInstance<IExceptionFilter>));
// ...
});
instead of
services.AddMvc(options =>
{
options.Filters.Add<HttpGlobalExceptionFilter>();
// ...
});
In my bindings:
container.Register<IExceptionFilter, HttpGlobalExceptionFilter>();
Finally, the dispatcher:
public sealed class SimpleInjectorExceptionFilterDispatcher : IExceptionFilter
{
private readonly Func<IExceptionFilter> exceptionFilterFunc;
public SimpleInjectorExceptionFilterDispatcher(
Func<IExceptionFilter> exceptionFilterFunc)
{
this.exceptionFilterFunc = exceptionFilterFunc;
}
public void OnException(ExceptionContext context)
{
this.exceptionFilterFunc.Invoke().OnException(context);
}
}
Is this the way to go about getting Simple Injector work with different components of ASP.NET? This is complex setup, and I would prefer to have something simpler so that all developers can easily understand the code.
Also, can I totally avoid Microsoft DI and use Simple Injector (and expect simpler configurations?)
References:
Simple Injector: Register ILogger<T> by using ILoggerFactory.CreateLogger<T>()