如何将 ILogger 传递到我的过滤器

And*_*son 7 c# asp.net-core asp.net-core-webapi exceptionfilterattribute

我有一个 ASP.NET Web APi 服务。

我使用 IExceptionFilter 添加了一个全局错误异常例程。

要注册该服务,我在 StartUp.cs 中包含以下内容:

services.AddMvc(options =>
{
    options.Filters.Add(new ErrorHandlingFilter()); 
});
Run Code Online (Sandbox Code Playgroud)

我的异常过滤器类是这样的:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,显然,我在这一行遇到编译错误:

 options.Filters.Add(new ErrorHandlingFilter()); 
Run Code Online (Sandbox Code Playgroud)

因为它期望我传递 ILogger 的实例。

但我在这里定义了 Ilogger:

// 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"));
Run Code Online (Sandbox Code Playgroud)

那么,如何将实例传递到异常过滤器而不重复呢?

注意:我承认这可能是个愚蠢的问题,但天气很热,所以大脑很疲惫。

Jos*_*ens 7

您应该使用 添加过滤器Add<T>,这使我们能够从 IoC 容器解析过滤器。这意味着您ILogWriter将在使用过滤器时被注入。

services.AddMvc(options =>
{
    options.Filters.Add<ErrorHandlingFilter>(); 
});
Run Code Online (Sandbox Code Playgroud)

除此之外,正如 Nkosi 评论所说,您typeof也可以使用这将触发与上述相同的行为。

services.AddMvc(options =>
{
  options.Filters.Add(typeof(ErrorHandlingFilter));
});
Run Code Online (Sandbox Code Playgroud)