Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a C# (managed) dll that I don't have?

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

like image 232
nonot1 Avatar asked Feb 10 '11 16:02

nonot1


3 Answers

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

like image 106
zihotki Avatar answered Sep 24 '22 00:09

zihotki


.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.

like image 36
Tedd Hansen Avatar answered Sep 26 '22 00:09

Tedd Hansen


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.

like image 27
Mark Booth Avatar answered Sep 24 '22 00:09

Mark Booth