当 .Net 加载程序集时以及如何更改此行为?
对于应用程序,我需要检查 Crystal Reports 运行时库的可用性。我尝试过的是:
void CheckCrystal()
{
try
{
CrystalDecisions.Windows.Forms.CrystalReportViewer test = new CrystalDecisions.Windows.Forms.CrystalReportViewer();
test.Dispose();
}
catch (System.Exception)
{
PTrace.Error("Some dependences needed to run Crystal Reports are not available.");
throw;
}
}
这不起作用,因为在调用该方法之前调用 CheckCrystal 的方法中抛出了有关缺少 Crystal 依赖项的 File.IOException 。就像.Net知道它在需要它之前需要汇编一样。这是真的吗?我怎样才能改变这种行为?
提前致谢。
for an application I need to check the availability of Crystal Reports runtime libraries. What I've tried is:
void CheckCrystal()
{
try
{
CrystalDecisions.Windows.Forms.CrystalReportViewer test = new CrystalDecisions.Windows.Forms.CrystalReportViewer();
test.Dispose();
}
catch (System.Exception)
{
PTrace.Error("Some dependences needed to run Crystal Reports are not available.");
throw;
}
}
This is not working because the File.IOException about the missing Crystal dependency is thrown in the method that calls CheckCrystal before calling the method. Is like .Net knows that it will need the assembly before needing it. Is this true? How can I change this behaviour?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是因为代码是按方法进行 JIT 编译的,因此当您第一次尝试调用
CheckCrystal()
时,.NET 首先尝试编译它,然后加载所有必需的和尚未加载的程序集。.NET 允许您拦截程序集解析失败的时刻。为此,请订阅
AppDomain.AssemblyResolve
事件。This is because code is JITted on a per-method basis, so when you first try to invoke
CheckCrystal()
, .NET first tries to compile it, subsequently loading all required and not-yet-loaded assemblies..NET allows you to intercept a moment when assembly resolution fails. To do so, subscribe to
AppDomain.AssemblyResolve
event.您可能想要处理
AppDomain.AssemblyResolve
事件。更多信息请参见此处。一个快速而肮脏的例子:
You would probably want to handle the
AppDomain.AssemblyResolve
event. More information here.A quick and dirty example:
为了提高启动性能,CLR 延迟加载程序集。
手动加载或处理
AppDomain.AssemblyResolve
事件。To improve startup performance the CLR lazily loads assemblies.
Either manually load or handle
AppDomain.AssemblyResolve
event.