Is it possible to instantiate an object at runtime if I only have the DLL name and the class name, without adding a reference to the assembly in the project? The class implements a interface, so once I instantiate the class, I will then cast it to the interface.
Assembly name:
library.dll
Type name:
Company.Project.Classname
EDIT: I dont have the absolute path of the DLL, so Assembly.LoadFile
won't work. The DLL might be in the application root, system32, or even loaded in the GAC.
I found this question and some answers very useful, however I did have path problems, so this answer would cover loading library by finding bin directory path.
First solution:
Second solution
You can use same principle for interfaces (you would be creating a class but casting to interface), such as:
This example is for web application but similar could be used for Desktop application, only path is resolved in different way, for example
Yes, it is, you will want to use the static Load method on the Assembly class, and then call then call the CreateInstance method on the Assembly instance returned to you from the call to Load.
Also, you can call one of the other static methods starting with "Load" on the Assembly class, depending on your needs.
Yes. I don't have any examples that I've done personally available right now. I'll post later when I find some. Basically you'll use reflection to load the assembly and then to pull whatever types you need for it.
In the meantime, this link should get you started:
Using reflection to load unreferenced assemblies at runtime
You can load an assembly using *Assembly.Load** methods. Using Activator.CreateInstance you can create new instances of the type you want. Keep in mind that you have to use the full type name of the class you want to load (for example Namespace.SubNamespace.ClassName). Using the method InvokeMember of the Type class you can invoke methods on the type.
Also, take into account that once loaded, an assembly cannot be unloaded until the whole AppDomain is unloaded too (this is basically a memory leak).
Consider the limitations of the different
Load*
methods. From the MSDN docs...More information on Load Contexts can be found in the
LoadFrom
docs.