Wednesday, February 27, 2008

Dynamically Load Assemblies in C# framework 3.5

Here are two simple examples of how to dynamically load assemblies in framework 3.5 using c#

This first file will be our assembly that we wish to load

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace plugin
{
public class plugin
{
private string _message;
public plugin()
{
_message = "I am just a plugin";
Console.WriteLine(_message);
}
}
public class pluginAdvanced{

public pluginAdvanced(string message, int times)
{
string[] array = new string[times];
for (int i = 0; i < times; i++)
{
Console.WriteLine(message);
}

}
}
}

Then the exe that loads the file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection; //<--------very important line

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// this first example just instantiates a class with no input parameters
Assembly dynamic = System.Reflection.Assembly.LoadFrom("./ClassLibrary1.dll"); // specify path to dll
object holder = Activator.CreateInstance(dynamic.GetType("plugin.plugin"));

// this second method instantiates a class that takes parameters
dynamic = System.Reflection.Assembly.LoadFrom("./ClassLibrary1.dll");
object[] passin = new object[2] { "I need to be heard", 2 };
holder = Activator.CreateInstance(dynamic.GetType("plugin.pluginAdvanced"),passin);

}
}
}


// good luck : )

No comments: