Loading assemblies, locating classes, and invoking methods dynamically presents unique challenges. This article details a secure and efficient method for accomplishing this task.
The common approach of directly loading a DLL and accessing its classes often leads to casting errors. A superior solution leverages the power of AppDomains.
Rather than directly loading the assembly, encapsulate it within its own AppDomain. This offers enhanced security and control.
The improved code example:
<code class="language-csharp">var domain = AppDomain.CreateDomain("NewDomainName"); var t = typeof(TypeIWantToLoad); var runnable = domain.CreateInstanceFromAndUnwrap(@"C:\myDll.dll", t.Name) as IRunnable; if (runnable == null) throw new Exception("broke"); runnable.Run();</code>
Here's a breakdown:
Employing AppDomains provides:
For advanced scenarios requiring more control over dynamic loading and unloading, the Managed Add-ins Framework (System.AddIn namespace) offers a robust and powerful solution for managing add-ins and extensions.
The above is the detailed content of How Can I Safely Load, Locate, and Execute a Class Method from a Dynamically Loaded Assembly?. For more information, please follow other related articles on the PHP Chinese website!