【发布时间】: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