How to load Assembly at runtime and create class instance?

58,261

Solution 1

If your assembly is in GAC or bin use the assembly name at the end of type name instead of Assembly.Load().

object obj = Activator.CreateInstance(Type.GetType("DALL.LoadClass, DALL", true));

Solution 2

You should Use Dynamic Method with for Improving. its faster than reflection..

Here is a sample code for creating Object using Dynamic Method..

public class ObjectCreateMethod
{
    delegate object MethodInvoker();
    MethodInvoker methodHandler = null;

    public ObjectCreateMethod(Type type)
    {
        CreateMethod(type.GetConstructor(Type.EmptyTypes));
    }

    public ObjectCreateMethod(ConstructorInfo target)
    {
        CreateMethod(target);
    }

    void CreateMethod(ConstructorInfo target)
    {
        DynamicMethod dynamic = new DynamicMethod(string.Empty,
                    typeof(object),
                    new Type[0],
                    target.DeclaringType);
        ILGenerator il = dynamic.GetILGenerator();
        il.DeclareLocal(target.DeclaringType);
        il.Emit(OpCodes.Newobj, target);
        il.Emit(OpCodes.Stloc_0);
        il.Emit(OpCodes.Ldloc_0);
        il.Emit(OpCodes.Ret);

        methodHandler = (MethodInvoker)dynamic.CreateDelegate(typeof(MethodInvoker));
    }

    public object CreateInstance()
    {
        return methodHandler();
    }
}

//Use Above class for Object Creation.
ObjectCreateMethod inv = new ObjectCreateMethod(type); //Specify Type
Object obj= inv.CreateInstance();

This method takes only 1/10th time needed by Activator.

Check out http://www.ozcandegirmenci.com/post/2008/02/Create-object-instances-Faster-than-Reflection.aspx

Solution 3

Check out http://www.youtube.com/watch?v=x-KK7bmo1AM To modify his code to load multiple assemblies use

static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {
            string assemblyName = args.Name.Split(',').First();
            using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("YourNamespace." + assemblyName + ".dll"))
            {
                byte[] assemblyData = new byte[stream.Length];
                stream.Read(assemblyData, 0, assemblyData.Length);
                return Assembly.Load(assemblyData);
            }
        }
In your main method put
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
Be sure to add your assemblies to your project and change the build action property to "Embedded Resource".
Share:
58,261
Pankaj
Author by

Pankaj

S/W Developer working on C#,ASP.NET and windows application.

Updated on November 30, 2020

Comments

  • Pankaj
    Pankaj over 3 years

    I have a assembly. In this assembly I have a class and interface. I need to load this assembly at runtime and want to create an object of the class and also want to use the interface.

    Assembly MyDALL = Assembly.Load("DALL"); // DALL is name of my dll
    Type MyLoadClass = MyDALL.GetType("DALL.LoadClass"); // LoadClass is my class
    object obj = Activator.CreateInstance(MyLoadClass);
    

    This is my code. How could it be improved?

  • paz
    paz over 10 years
    Is there no need to specify the name of the assembly?
  • DRobertE
    DRobertE about 10 years
    How can this be change to call constructors with parameters such as another object?