【问题标题】:Web API - Inject dependency at ServiceContainer using UnityWeb API - 使用 Unity 在 ServiceContainer 中注入依赖项
【发布时间】:2018-10-08 20:05:47
【问题描述】:

我正在使用ExceptionLogger 来处理所有全局异常。我的继承类需要注入依赖项以供 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);
    }
}

LoggingService 类:

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

我的统一代码:

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: 'RuntimeType 类型必须派生自 IExceptionLogger。'

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

关于如何在注册服务时解决依赖关系的任何想法?

【问题讨论】:

  • 您是否正确设置了依赖解析器?并且在添加服务时添加实例。 config.Services.Add(typeof(IExceptionLogger), {instance here});
  • @Nkosi:是的,我已经用解析器代码编辑了这个问题。
  • 对了,我建议你在添加服务之前设置一下

标签: c# asp.net-web-api dependency-injection unity-container


【解决方案1】:

将服务添加到ServicesContainer 时,您将类型与服务实例一起添加。

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

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

异常记录器和异常处理程序之间也有区别。

我建议查看以下参考链接以确定哪个适合您的需求。

参考Global Error Handling in ASP.NET Web API 2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-05
    相关资源
    最近更新 更多