How to detect a missing .NET reference at runtime?

拜拜、爱过 提交于 2019-12-06 00:52:41

问题


My application contains references to an external library (the SQL Server Management Objects). Apparently, if the library is not present on the run-time system, the application still works as long as no methods are called that use classes from this library.

Question 1: Is this specified behaviour or just a (lucky) side effect of the way the CLR loads libraries?

To detect whether the reference is accessible, I currently use code like this:

Function IsLibraryAvailable() As Boolean
    Try
        TestMethod()
    Catch ex As FileNotFoundException
        Return False
    End Try
    Return True
End Function

Sub TestMethod()
    Dim srv As New Smo.Server()  ' Try to create an object in the library
End Sub

It works, but it seems to be quite ugly. Note that it only works if TestMethod is a separate method, otherwise the exception will be thrown at the beginning of IsLibraryAvailable (before the try-catch, even if the object instantiation occurrs within the try-catch block).

Question 2: Is there a better alternative?

In particular, I'm afraid that optimizations like function inlining could stop my code from working.


回答1:


That is expected, since the JIT is lazy at the per-method level. Note that inlining isn't an issue here, since that is also a JIT concern, not a compiler concern.

Better options:

  • make sure the app is installed with everything it needs
  • using ilmerge or similar to create a single assembly (if possible)

Personally, I'd just use the first option.



来源:https://stackoverflow.com/questions/6847765/how-to-detect-a-missing-net-reference-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!