Web API - 使用 Unity 在 ServiceContainer 注入依赖

Web API - Inject dependency at ServiceContainer using Unity

我正在使用 ExceptionLogger 来处理所有全局异常。我的继承 class 需要为 Nlog 注入依赖项才能调用。

public class NLogExceptionLogger : ExceptionLogger
{
    private readonly ILoggingService _loggingService;

    public NLogExceptionLogger(ILoggingService<NLogExceptionLogger> loggingService)
    {
        _loggingService = loggingService;
    }

    public override void Log(ExceptionLoggerContext context)
    {
        _loggingService.FirstLevelServiceLog(context.Exception.StackTrace);
    }
}

日志服务Class:

public class LoggingService<T> : ILoggingService<T>
{
    private readonly ILogger _logger;

    public LoggingService()
    {
        string currentClassName = typeof(T).Name;
        _logger = LogManager.GetLogger(currentClassName);
    }

    public void FirstLevelServiceLog(string log)
    {
        _logger.Log(LogLevel.Debug, log);
    }
}

我的Unity代码:

public static UnityContainer RegisterComponents()
{
    var container = new UnityContainer();
    container.RegisterType(typeof(ILoggingService<>), typeof(LoggingService<>))
}

我正在通过以下方式在全球范围内注册 ExceptionLogger:(在这一行我遇到了错误)

config.Services.Add(typeof(IExceptionLogger), typeof(NLogExceptionLogger));
//Register Dependency Container
config.DependencyResolver = new UnityDependencyResolver(UnityConfig.RegisterComponents());

我在运行时遇到以下错误:

System.ArgumentException: 'The type RuntimeType must derive from IExceptionLogger.'

我的假设是我没有正确注册 NLogExceptionLogger 的依赖项。

知道如何在注册服务时解决依赖关系吗?

将服务添加到 ServicesContainer 时,您会添加带有服务实例的类型。

假设已经设置了依赖解析器,如果它有依赖关系,它可以用来解析实例。

var logger = config.DependencyResolver.GetService(typeof(NLogExceptionLogger));
config.Services.Add(typeof(IExceptionLogger), logger);

异常记录器和异常处理程序之间也存在差异。

我建议查看以下参考资料 link 以确定哪一个适合您的需求。

引用Global Error Handling in ASP.NET Web API 2