Can a referenced DLL be loaded even if it's no

2019-07-13 15:18发布

问题:

Env.: .NET / VS2008

Hi All,

My app uses a 3rd party DLL assembly separately installed on some systems (clearly identified) but not all of them.

Which means that on some systems, the DLL is not there hence must not be called. To solve this, I have 2 versions of the app (using 2 configurations) for the 2 use cases. In one of them, all calls to the DLL are #if'ed out.

Since there are no calls to the DLL compiled at all in the app(they're #if'ed out), is it safe to assume that the app won't try to load the DLL even though it is referenced?

Or should I also exclude the reference?

Note: Asked in reaction to womp's comment in this question.

TIA,

回答1:

IIRC, the C# compiler will omit references to dll's that are never actually used in the code. So if all code is inside #ifs, the reference to the dll will not be there in your compiled app, and the dll will never be loaded.

You can check this using Reflector, by the way. Just drag & drop your compiled app into Reflector, and look at the References node. ILDASM also provides this feature, I think.

Caveat: DllImports and dynamic type loading (e.g., Type.GetType("type,dll")) will dynamically load dlls without the C# compiler knowing or caring. But again, if inside the proper #ifs, nothing will be loaded.



回答2:

I would exclude it. It might load it no matter what and if you have a type reference, then that also could cause a problem.



回答3:

Why not load the the assembly dynamically if needed/available? And then if its gets added at a later date you can just make use of it? You'll only need one version of your app also.



回答4:

You are safe with a reference but without the actual DLL if you never (obviously) instantiate and referenced class AND never refer to the Class in any instantiated or referenced object.

Typically your DLL will be loaded the first time the Class Constructor of a referenced Class is run.

HTH Jan



标签: c# .net clr