Dynamic loading of assemblies and instantiated classes at runtime
Knowing only the DLL file name and class name, is it possible to instantiate an object at runtime without explicitly referencing the assembly in the project? This class usually implements an interface that allows type conversion after instantiation.
Assembly name: library.dll Type name: Company.Project.Classname
No file path
Cannot be used since there is no absolute DLL path. The DLL may be located in the application root, system32, or the GAC. Assembly.LoadFile
Solution
It can be done. Use to load an assembly into memory. Then, use Assembly.LoadFrom
to generate an instance of the desired type. First use reflection to find the type. Activator.CreateInstance
<code class="language-csharp">Assembly assembly = Assembly.LoadFrom("MyNice.dll"); Type type = assembly.GetType("MyType"); object instanceOfMyType = Activator.CreateInstance(type);</code>
Improved solution
Given an assembly file name and a type name, can be resolved to a type. This can be wrapped with a try/catch block for error handling. If that fails, directories where other assemblies may exist are searched and the previous methods are applied if necessary. Activator.CreateInstance(assemblyName, typeName)
The above is the detailed content of Can I Instantiate a Class at Runtime Knowing Only its DLL and Type Name?. For more information, please follow other related articles on the PHP Chinese website!