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?
Asked
Active
Viewed 4,468 times
0
-
2Possible 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 Answers
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" });
-
Thanks. How would you call the properties of the new object? can not use object.MyProperty, right? – NewDTinStackoverflow Apr 16 '13 at 17:39
-
Of course you can same way as call method below. Just use GetProperties – Piotr Stapp Apr 16 '13 at 17:59
-
One more question, if the dll being loaded needs another dll, could I load multiple dlls the same time? It does not seem working.... – NewDTinStackoverflow Apr 16 '13 at 21:59
-
If that dll is in the same directory it should find it automagically. If it doesn't have a look at the basedir of your current `AppDomain`. – albertjan Apr 17 '13 at 12:36
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