How can I correctly reference a C# DLL that I don't have physical access to? (I actually have the DLL, just not all it's dependencies.)
Background:
On the target computer, there is a program and many interdependent dll files installed in C:\FancyProgram
.
I need to write a simple application that will be deployed on the target computer to C:\SimpleProgram
.
This simple program will need to make some calls into one of the dll files under C:\FancyProgram
. It is a .net managed DLL
On my development machine, I do not have a copy of FancyProgram
. I do have that one DLL file, but I do not have any of it's many dependencies. I also can not bundle that DLL into SimpleProgram
.
What is the correct method to use and reference this DLL in my Visual Studio project such that my SimpleProgram
will correctly compile but load the DLL at runtime from the correct location?
Thank you
My recommendation is to create a Facades for the functionality you want to use from that dll. And don't use (reference) it directly - resolve and load it dynamically:
C# - Correct Way to Load Assembly, Find Class and Call Run() Method
Load Assembly at runtime and create class instance
.Net will do late binding anyway. As long as you don't reference the .dll in any way until you actually mean to load it this will work.
Simply encapsulate all references (fields, properties, methods, instances) into a spearate class or project and make an instance only when you have to. You can then try-catch the load error. See Visual Studio Output window when your app is run, it will tell you when its is attempting to load what .dll.
You may also want to look at these events to make your app handle errors gracefully:
AppDomain.CurrentDomain.AssemblyLoad += ...;
AppDomain.CurrentDomain.AssemblyResolve += ...;
AppDomain.CurrentDomain.UnhandledException += ...;
AppDomain.CurrentDomain.FirstChanceException += ...;
You may also want to take the MEF approach. It is a framework for doing late loading/binding.
You might want to look at the details of LoadLibrary
, GetProcAddress
and Marshal.GetDelegateForFunctionPointer
.
I would also build dll for testing locally, with the same interface as your external dll. How much functionality yo put in there depends on the complexity of the interface and your SimpleProgram
.
There were some excellent answers to my old question about importing external dlls.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With