代码之家  ›  专栏  ›  技术社区  ›  Andrew Simpson

如何将ilogger传递给我的过滤器

  •  2
  • Andrew Simpson  · 技术社区  · 7 年前

    我有一个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实例。

    但我在这里定义了我自己:

    // 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"));
    

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

    铌 我承认这可能是愚蠢的问题,但它是非常热的,所以大脑是疲乏的。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Josh Stevens    7 年前

    您应该使用添加筛选器 Add<T> ,这允许我们从IOC容器解析过滤器。这意味着你的 ILogWriter 将在使用过滤器时为您注入。

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

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

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