上周我的Windows服务应用程序部署到生产中失败了,所以我尝试在发布模式下本地运行项目,并获得InvalidOperationException: Can not determine current class.
,这被追溯到GetCurrentClassLogger
的调用。
我的项目使用 Ninject 将ILoggerFactory
解析为中间层中的每个服务。然后,该服务使用GetCurrentClassLogger()
在构造函数中获取正确的ILogger
。
例如:
public class FooService : IFooService
{
private readonly ILogger logger;
public FooService(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.GetCurrentClassLogger();
}
// ...
}
如果我在 Ninject.Extensions.Logging 的GetCurrentClassLogger
深入研究LoggerFactoryBase
的实施:
[MethodImpl(MethodImplOptions.NoInlining)]
public ILogger GetCurrentClassLogger()
{
StackFrame stackFrame = new StackFrame(0, false);
if (stackFrame.GetMethod() == (MethodBase) LoggerFactoryBase.getCurrentClassLoggerMethodInfo)
stackFrame = new StackFrame(1, false);
Type declaringType = stackFrame.GetMethod().DeclaringType;
if (declaringType == (Type) null)
throw new InvalidOperationException(string.Format("Can not determine current class. Method: {0}", (object) stackFrame.GetMethod()));
return this.GetLogger(declaringType);
}
我可以看到抛出异常的位置。
我的第一直觉是检查是否有任何系统,框架或项目更新导致它,但自上次成功部署以来没有做任何有意义的事情。
现在......关于这个问题的“有趣”的事情是,当我在构造函数中添加一行Trace.WriteLine("Test");
时,GetCurrentClassLogger
执行得很好。
我能够将此问题与编译器的代码优化联系起来。如果我在项目属性的 Build 选项卡中禁用它,它也可以正常执行。
问题:什么可能导致StackFrame
停止提供DeclaringType
?
同时我使用它作为解决方法,但我更喜欢使用原始方法:
this.logger = loggerFactory.GetLogger(this.GetType());
非常感谢任何帮助。
答案 0 :(得分:4)
在没有查看正在发出的CIL的情况下,很难说完全为什么行为会有所不同,但我猜它会被内联。 如果将构造函数归属于:
,则可能会得到所需的结果[MethodImpl(MethodImplOptions.NoInlining)]
正如NInject代码所做的那样。该方法可能会被内联,因为它只是一行分配了一个只读字段。您可以在此处阅读有关内联如何影响StackFrame的内容:http://www.hanselman.com/blog/ReleaseISNOTDebug64bitOptimizationsAndCMethodInliningInReleaseBuildCallStacks.aspx
那就是说,这种不可预测性是为什么使用堆栈帧是一个坏主意。如果您希望不必指定类名的语法,使用VS 2012,并且您的文件名与您的类名匹配,则可以在扩展方法上使用CallerFilePath属性并保留与现在相同的行为,而不使用堆栈帧。看到: https://msdn.microsoft.com/en-us/library/hh534540.aspx
更新:
另一种方法可能是直接注入ILogger并让容器负责确定要注入的组件的类型(因为它肯定知道)。这似乎也更清洁。请参阅此处的示例:https://github.com/ninject/ninject.extensions.logging/issues/19
this.Bind<ILogger>().ToMethod(context =>
{
var typeForLogger = context.Request.Target != null
? context.Request.Target.Member.DeclaringType
: context.Request.Service;
return context.Kernel.Get<ILoggerFactory>().GetLogger(typeForLogger);
});