Correct Way to Load Assembly, Find Class and Call Run() Method

前端 未结 5 951
刺人心
刺人心 2020-11-22 12:17

Sample console program.

class Program
{
    static void Main(string[] args)
    {
        // ... code to build dll ... not written yet ...
        Assembly a         


        
5条回答
  •  自闭症患者
    2020-11-22 12:38

    Use an AppDomain

    It is safer and more flexible to load the assembly into its own AppDomain first.

    So instead of the answer given previously:

    var asm = Assembly.LoadFile(@"C:\myDll.dll");
    var type = asm.GetType("TestRunner");
    var runnable = Activator.CreateInstance(type) as IRunnable;
    if (runnable == null) throw new Exception("broke");
    runnable.Run();
    

    I would suggested the following (adapted from this answer to a related question):

    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();
    

    Now you can unload the assembly and have different security settings.

    If you want even more flexibility and power for dynamic loading and unloading of assemblies you should look at the Managed Add-ins Framework (i.e. the System.AddIn namespace). For more information see this article on Add-ins and Extensibility on MSDN.

提交回复
热议问题