0

I want to load a dll from another applications at run time but at the same time, I need to create an instance of a class implemented in the dll. Could it be done? I could load dlls at run time and there are some examples for them but how could I call a class without the dll being loaded? Won't compile, right?

  • 2
    Possible duplicate [Load Assembly at runtime and create class instance](http://stackoverflow.com/questions/1803540/load-assembly-at-runtime-and-create-class-instance) – Vamsi Apr 16 '13 at 06:58
  • [How to: Load Assemblies into an Application Domain](http://msdn.microsoft.com/en-us/library/25y1ya39.aspx) – Sen Jacob Apr 16 '13 at 07:00
  • [How to: Unload an Application Domain](http://msdn.microsoft.com/en-us/library/c5b8a8f9.aspx) – Sen Jacob Apr 16 '13 at 07:01

2 Answers2

2

You can load a dll in runtime.

like this:

//load assembly
var assembly = Assembly.LoadFile("ADll.dll");

//get types from assembly
var typesInAssembly = assembly.GetTypes();

var type = typesInAssembly.First(/*select one*/);

//create instance
var object = Activator.CreateInstance(type, new object [] { "arguments" });
2ps
  • 15,099
  • 2
  • 27
  • 47
albertjan
  • 7,739
  • 6
  • 44
  • 74
1

It will compile. The easiest way is to have common interface with your app and loaded dll. Hot to do this you can find here: C# - Correct Way to Load Assembly, Find Class and Call Run() Method.

But if you do not have common interface still you can CreateInstance, then find all method you need (below example is for all methods):

MethodInfo[] methodInfos = Type.GetType(selectedObjcClass) .GetMethods(BindingFlags.Public | BindingFlags.Instance);

And then call selected one using Invoke like this:

method.Invoke(selectedObjcClass, params...);   
Community
  • 1
  • 1
Piotr Stapp
  • 19,392
  • 11
  • 68
  • 116