Dynamically Instantiate Objects from Another Assembly within the Current AppDomain

Reflection is one of the coolest features in .Net.  But to support instantiation of objects from different assemblies within your application domain requires a little finagling:

 
// try this assembly first; full className e.g. MyNameSpace.Pattern.MyClass
Type typeToCreate = Type.GetType(className);
 
if (typeToCreate == null) // try the others in the same domain
{
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly assembly in assemblies)
{
if (assembly.FullName.StartsWith("MyNamespace.Pattern")) // only my site dlls
{
typeToCreate = assembly.GetType(className, false);
if (typeToCreate!= null) { break; } // escape the loop because you have your type
}
}
}
 
 
if (typeToCreate!= null)
{
Activator.CreateInstance(typeToCreate);
// do more stuff ;)
}
else
{
throw new ApplicationException(className + " type could not be found.");
}

And there you have it.  You would also probably want to have those objects that you wish to create to share some sort of common interface so you can use it after you instantiate it.

This entry was posted in C#. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *