C# – How to load DLL in separate domain and use its methods?


Sometimes you may have a need to load a DLL in a separate domain to call its method at run-time. You can create a proxy class by referencing the following code snippet:

public class Loader : MarshalByRefObject
 {
     object CallInternal(string dll, string typename, string method, object[] parameters)
     {
         Assembly a = Assembly.LoadFile(dll);
         object o = a.CreateInstance(typename);
         Type t = o.GetType();
         MethodInfo m = t.GetMethod(method);
         return m.Invoke(o, parameters);
     }
     public static object Call(string dll, string typename, string method, params object[] parameters)
     {
         AppDomain dom = AppDomain.CreateDomain("MyNewDomain");
         Loader ld = (Loader)dom.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, typeof(Loader).FullName);
         object result = ld.CallInternal(dll, typename, method, parameters);
         AppDomain.Unload(dom);
         return result;
     }
 }
Comments (4)

  1. Rafael Azevedo says:

    I’m very thankful !!! It worked very well to me!!!

  2. Jorge says:

    Can you provide an example of how it’s used please?

  3. Peter says:

    Nice code. Many thanks, guy!

  4. samas says:

    Will you please provide with example…