【发布时间】:2018-08-28 16:58:13
【问题描述】:
我在 ASP.NET Core 2.1 WebAPI 应用程序中使用 Simple Injector。我有一个 IExceptionFilter,我想在其中记录错误。我的代码在下面(工作),但这是正确的方法吗?看起来工作量很大
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;
}
}
在我的 Startup.cs ConfigureServices() 中,我有:
services.AddMvc(options =>
{
options.Filters.Add(new SimpleInjectorExceptionFilterDispatcher(
this.container.GetInstance<IExceptionFilter>));
// ...
});
而不是
services.AddMvc(options =>
{
options.Filters.Add<HttpGlobalExceptionFilter>();
// ...
});
在我的绑定中:
container.Register<IExceptionFilter, HttpGlobalExceptionFilter>();
最后是调度员:
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);
}
}
这是让 Simple Injector 与 ASP.NET 的不同组件一起工作的方法吗?这是一个复杂的设置,我希望有一些更简单的东西,以便所有开发人员都可以轻松理解代码。
另外,我是否可以完全避免使用 Microsoft DI 并使用 Simple Injector(并期望更简单的配置?)
参考资料:
Simple Injector: Register ILogger<T> by using ILoggerFactory.CreateLogger<T>()
【问题讨论】:
标签: c# asp.net-core simple-injector