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.

Comments

  1. Anonymous5:56 PM

    Peter,

    Maybe I'm just being thick but how do you get the IMessage interface to compile (not having defined the YourClassToProcess)

    Thanks for all the great articles...

    ReplyDelete
  2. Anonymous12:08 PM

    I'm getting the ubiquitous "Unable to cast object of type 'System.Runtime.Remoting.ObjectHandle' to type '[my type]'." message. Then again, I am trying to Create the instance based on a string name, not an actual object type.

    ReplyDelete

Post a Comment

Popular posts from this blog

FIREFOX / IE Word-Wrap, Word-Break, TABLES FIX

Some observations on Script Callbacks, "AJAX", "ATLAS" "AHAB" and where it's all going.

IE7 - Vista: "Internet Explorer has stopped Working"