Freigeben über


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

  • Anonymous
    March 31, 2014
    I'm very thankful !!! It worked very well to me!!!
  • Anonymous
    October 12, 2014
    Can you provide an example of how it's used please?
  • Anonymous
    January 14, 2015
    Nice code. Many thanks, guy!
  • Anonymous
    July 29, 2015
    Will you please provide with example...