I am working on a web application that doesn't require support for plug-ins, but has a couple of pieces of important functionality that I know will be enhanced in the future as the web application matures. When I identify such parts of an application, I typically will:
- Isolate each part from the core engine by putting it in its own assembly
- Reference the functionality in terms of an Interface
- Use a Factory Method in the core engine to instantiate the actual object
In this case, I also wanted to go a step further and place the classes to instantiate in the application settings of the Web.Config file. I also could have created a custom configuration section or even a separate XML file for that matter, but it really isn't necessary. I added each class in the Web.Config as such, where I specified the key, the class name, and the name of the assembly.
<appSettings>
<add key=“{key}" value="{class name}, {Assembly Name}" />
</appSettngs>
One can then use a Factory Method to dynamically instantiate and invocate the class:
ISomething something = Site.GetSomething();
where Site.GetSomething() looks like:
public static ISomething GetSomething()
{
return (ISomething)Activator.CreateInstance(Type.GetType(ConfigurationSettings.AppSettings[“key“));
}
This works really sweet and gives me the loose coupling I was hoping for. Obviously you need to do some exception handling here. I am just showing the overall idea.
For more information on creating a plug-in framework and finding plug-ins dynamically, check out the articles on MSDN here and here.