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.
So in this way you can use functions not with getting methodinfo,and then invoking it.You will do like this instanceOfMyType.MethodName(); But you can't use Intellisense because dynamic types are typed in runtime,not in compile time.
Depending how intrinsic this kind of functionality is to your project, you might want to consider something like MEF which will take care of the loading and tying together of components for you.
Starting from Framework v4.5 you can use Activator.CreateInstanceFrom() to easily instantiate classes within assemblies. The following example shows how to use it and how to call a method passing parameters and getting return value.
Yes. You need to use
Assembly.LoadFrom
to load the assembly into memory, then you can useActivator.CreateInstance
to create an instance of your preferred type. You'll need to look the type up first using reflection. Here is a simple example:Update
When you have the assembly file name and the type name, you can use
Activator.CreateInstance(assemblyName, typeName)
to ask the .NET type resolution to resolve that into a type. You could wrap that with a try/catch so that if it fails, you can perform a search of directories where you may specifically store additional assemblies that otherwise might not be searched. This would use the preceding method at that point.It's Easy.
Example from MSDN:
Here's a reference link
https://msdn.microsoft.com/en-us/library/25y1ya39.aspx
You can do this things on this way: