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

时间:2018-07-19 19:56:58

标签: c# asp.net-core asp.net-core-webapi exceptionfilterattribute

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

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

要注册服务,请在StartUp.cs中使用它:

services.AddMvc(options =>
{
    options.Filters.Add(new ErrorHandlingFilter()); 
});

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

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

但是,很明显,我在此行遇到编译错误:

 options.Filters.Add(new ErrorHandlingFilter()); 

因为它希望我传递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"));

那么,如何在不重复的情况下将实例传递给我的异常过滤器?

NB 我承认这可能是一个愚蠢的问题,但是它非常热,使大脑感到疲倦。.

1 个答案:

答案 0 :(得分:1)

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

services.AddMvc(options =>
{
    options.Filters.Add<ErrorHandlingFilter>(); 
});

最重要的是,Nkosi评论说,您也可以使用typeof,这将触发与上述相同的行为。

services.AddMvc(options =>
{
  options.Filters.Add(typeof(ErrorHandlingFilter));
});
相关问题