Using AppDomain in C# to dynamically load and unload dll

前端 未结 4 1043
無奈伤痛
無奈伤痛 2020-11-29 07:44

In one of my application, which is related to system diagnostics, the related DLL is to be loaded and unloaded dynamically in C#. After some search I found that a separate D

4条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 08:34

    How to: Load Assemblies into an Application Domain

    public static void Main()
    
    
        {
            // Use the file name to load the assembly into the current
            // application domain.
            Assembly a = Assembly.Load("example");
            // Get the type to use.
            Type myType = a.GetType("Example");
            // Get the method to call.
            MethodInfo myMethod = myType.GetMethod("MethodA");
            // Create an instance.
            object obj = Activator.CreateInstance(myType);
            // Execute the method.
            myMethod.Invoke(obj, null);
        }
    

    As for how to unload it, you have to unload the AppDomain itself, see this

    AppDomain Temporary = AppDomain.CreateDomain("Temporary");
    try
    {
      Gateway Proxy = 
        (Gateway) Temporary.CreateInstanceAndUnwrap("Shim", "Shim.Gateway");
    
      Match M = Proxy.LoadAndMatch("Plugin.dll", 
        "Though the tough cough and hiccough, plough them through");  
    }
    finally
    {
      AppDomain.Unload(Temporary);
    }
    

提交回复
热议问题