1/13/2006

Activator.CreateInstance Pattern with Interface

This has come up several times already in newsgroup and forum posts, so I thought I would post my "keep it smple" implementation here. What we want to do is be able to load an assembly dynamically, create an instance of a named class, and call a method with parameters. The information we need to do this probably comes out of a database.

First, I start with an interface:

public interface IMessage
{
NameValueCollection Parameters { get; set; }
DateTime DateTimeCreated { get; set; }
bool Success { get; set; }
Exception OperationException { get; set; }
IMessage Execute(YourClassToProcess yourClass);

}

The IMessage interface defines a NameValueCollection (which name-values could also be coming out of associated rows in another database table), a bool for Success, and an Exception object.
By simply populating a NameValue Collection with our parameter names and values, and assigning this to the IMessage Parameters field, the internal implementation can get all the parameters it needs for its specific operation.

Its Execute method also accepts a class of your choosing, and returns another IMessage interface object to hold the result. Simple!

Now here is a method to use all this:

private void ExecuteMethodOnAssembly( string assemblyName,
string className,
YourClassToProcess yourClass,
NameValueCollection parameters)
{
Type ObjType = null;
IMessage im;
try
{
// load it
Assembly ass = null;
ass = Assembly.Load(assemblyName);
if (ass != null)
{

ObjType = ass.GetType(className);
}
}
catch (Exception ex)
{
// whatever you need to do here
}
try
{
// OK Lets create the object
if (ObjType != null)
{
im = (IMessage)Activator.CreateInstance(ObjType);
im.Parameters=parameters;
IMessage resMsg= im.Execute(yourClass) ;
if(resMsg.Success ==false)
// whatever you need to do
}
}
catch (Exception ex)
{
// whatever you need to do
}
} // end Method ExecuteMethodOnAssembly


I have found that this arrangement, or similar ones, provides the most flexibility. Note the use of the interface means we don't care what assembly or class we are using, as long as it implements IMessage, we are fine.