C# – Using AppDomain in C# to dynamically load and unload dll


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 DLL cannot be loaded dynamically its the complete AppDomain. So I have to create an AppDomain and use that DLL to be loaded unloaded dynamically. But I could not find anywhere how can I use that in code. I can not show the app code since it is against company rules.

Can somebody tell me some application code to use it. I want to load and unload the dll dynamically using appdomain and call a specific method in that dll, the dll does not have any entry point.

Thanks for answers.

Best Solution

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");
  Gateway Proxy = 
    (Gateway) Temporary.CreateInstanceAndUnwrap("Shim", "Shim.Gateway");

  Match M = Proxy.LoadAndMatch("Plugin.dll", 
    "Though the tough cough and hiccough, plough them through");