在Asp Dot Net MVC Core中注册全局异常过滤器

时间:2019-04-03 13:27:57

标签: .net-core

我正在Asp.Net Core 2.2应用程序中实现全局异常过滤器。 为此,我创建了GlobalExceptionLogger类,该类在其构造函数中将Ilog类型参数作为DI。

CustomeLogger类已实现此ILog接口,而我的CustomerLogger类期望ILogger记录器在其构造函数中为DI。

现在,我在启动类中将GlobalExceptionLoger注册为

services.AddMvc(option => {                 option.Filters.Add(new GlobalExceptionLogger());

但是不知道如何提供相关的依赖项来使其工作。

public class GlobalExceptionLogger : IExceptionFilter
{
    ILog log;
    public GlobalExceptionLogger(ILog log)
    {
        this.log = log;                
    }


    public void OnException(ExceptionContext context)
    {
        log.Log(LogEntryLevel.Error, context.Exception.Message);
    }


}


public class CustomeLogger : ILog
{
    private ILogger _logger;

    public CustomeLogger(ILogger<CustomeLogger> logger)
    {
        _logger = logger;
    }

    public void Log(LogEntryLevel level, string message, params object[] args)
    {
         //Code
    }
}

   //In StartUp.cs file
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<ILog, CustomeLogger>();

        services.AddMvc(option=> {
            option.Filters.Add(new GlobalExceptionLogger());
        });
    }

0 个答案:

没有答案
相关问题