Monday, January 14, 2008

How to activate one class object by class name


Keywords: Assembly, Activator, CreateInstance


If you use plug-in architecture, you will encounter how to activate one class object dynamically. There are 2 different scenarios.
(1)How to load class object by its class name in the same assembly. Please refer to Load Class().


(2)How to load class object in another assembly? Please refer to LoadPlugin_1() and LoadPlugin_2()




/// <summary>
/// Load class object in the same assembly
/// </summary>
private void LoadClass()
{
string type = "BT.DocxRichTextWriter";
//BT.DocxRichTextWriter is class full qualified name
string classTypeStr = type;
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
Type classType = assembly.GetType(classTypeStr);
object pluginObject = Activator.CreateInstance(classType);
}


/// <summary>
/// Load plugins by method 1
/// </summary>
private void LoadPlugin_1()
{
string type = "BT.DocxRichTextWriter, DocxSimpleObjWriter";
//BT.DocxRichTextWriter is class full qualified name, DocxSimpleObjWriter is assembly name with out extension.

string classFullType = type;
string[] classInfo = classFullType.Split(',');
System.Reflection.Assembly assembly = System.Reflection.Assembly.Load(classInfo[1]);
Type classType = assembly.GetType(classInfo[0]);
object pluginObject = Activator.CreateInstance(classType);
}

/// <summary>
/// load plugin by method 2
/// </summary>
private void LoadPlugin_2()
{
string type = "BT.DocxRichTextWriter, DocxSimpleObjWriter";
//BT.DocxRichTextWriter is class full qualified name, DocxSimpleObjWriter is assembly name with out extension.

string classFullType = type;
object pluginObject = Activator.CreateInstance(Type.GetType(classFullType));
}

No comments: