Blue Theme Orange Theme Green Theme Red Theme
 
MindFusion's Components
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Web Services » Introduction to Building a Plug-In Architecture Using C#

Introduction to Building a Plug-In Architecture Using C#

In this article we'll take another look at how we can use the state pattern to build a plug-in architecture that will allow us to change the behavior of our application by placing differnt plug-ins into a folder.

Author Rank:
Total page views :  52961
Total downloads :  1667
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
PluggableHostApplication.zip
 
Become a Sponsor

Part I. Overview

Using this technique, we will use the standard GOF State Pattern by having a host application expose a piece of functionality as interface. The host will then load different implementations based on some criteria that we'll be choosing. Once we have a class that implements this interface, it can be "plugged" into the host application by dropping the containing dll into a specified folder which provides the host application with a "pluggable" implementation of the exposed interface.

For this article we'll be using a the following very simple interface that will allow us to build plug-in components that the host can use to perform a calculation on two integers and expose the symbol representing the calculation. (Of course, in a real application the interface for the plug-in would probably be much more complex but we'll keep it simple here to keep the focus on the technique.)

public interface ICalculator
{
     int Calculate(int a, int b);
     char GetSymbol();
}

We could have multiple implementations of this interface in our main project or in seperate assemblies that would all look similiar to this class with slightly different implementations:

class Divider:ICalculator
{
    
#region ICalculator Members

     public int Calculate(int a, int b)
     {
         
return a / b;
     }

     public char GetSymbol()
     {
         
return '/';
     }

     #endregion
}

Injecting our implementation of the ICalculator interface with the constructor, we could provide a default behavior (division) for a host class while at the same time allowing for other implementations to be injected into our host class. This pattern also makes the host class easier to unit test.

public class CalculatorHost    
{
    
public CalculatorHost(ICalculator calculator)
     {
          m_calculator = calculator;
     }

     public CalculatorHost() : this(new Divider()) { }

     private int m_x, m_y;
    
private ICalculator m_calculator;

     public int X     
     {
         
get { return m_x; }
         
set { m_x = value; }
     }

     public int Y
     {
         
get { return m_y; }
         
set { m_y = value; }
    
}

     public int Calculate()
     {
         
return m_calculator.Calculate(m_x, m_y);
     }

     public override string ToString()
     {
         
return string.Format("{0} {1} {2} = {3}",
              
m_x.ToString(),
               m_calculator.GetSymbol(),
               m_y.ToString(),
               m_calculator.Calculate(m_x, m_y));
     }

}

Part II. Late Binding

What we want to be able to do at the end of the day, is drop a new dll implementing ICalculator into a folder and have the application be able to consume and use the new functionality through a late binding mechanism. For this particular implementation we'll be placing all the plug-in dlls in a folder called "Plugins" which will a sub directory where the main application's assembly lives. (Note: Because this is just a sample app and not bullet-proof, when you unzip and build the samples, you may have to manually add the "Plugins" sub-folder to avoid a runtime exception. Of course, you'll also have to place the plug-in dlls into this folder for the host application to load them.).

Because our late-binding mechanism uses reflection we will be taking a perf hit. One way to minimize the impact is to try to cache the results of this operation. In order to do this, we'll use a static class to hold the results of our binding. One approach would be to perform our late binding when the application starts. In this particular implementation we'll use the lazy-load approach and create a loader method that will populate a list of CalculatorHost objects and so we will take the hit the first time the application requests the plugins (which will probably be early in the life of the application).

public static class CalculatorHostProvider
{

     private static List<CalculatorHost> m_calculators;

     public static List<CalculatorHost> Calculators
     {
          get 
          {
               if (null == m_calculators)
                    Reload();

               return m_calculators; 
          }
     }
}

When Reload() is called for the first time, we will create the new list. We also may want to reload the plugins while our application is running. For instance, if we have dropped a new implementation in the "Plugings" subdirectory and can't afford to restart the application. In this case, we'll clear the existing calculators list.

Next we'll load all the assemblies in the "Plugins" subdirectory and iterate through them to locate the ones that we can use for creating a new CalculatorHost object.

public static void Reload()
{

     if (null == m_calculators)
          m_calculators =
new List<CalculatorHost>();
    
else
         
m_calculators.Clear();

     m_calculators.Add(new CalculatorHost()); // load the default
     List<Assembly> plugInAssemblies = LoadPlugInAssemblies();
     List<ICalculator> plugIns = GetPlugIns(plugInAssemblies);

     foreach (ICalculator calc in plugIns)
     {
          m_calculators.Add(
new CalculatorHost(calc));
     }
}

Part III. Attributes

While not absolutely required for this technique, it is a good idea to explicitly declare our plugins to ensure that the intent of the interface implementation is actually for a plug in component for our host application. In order to do this we'll use a custom attribute decorator for any class that will be implementing ICalculator and is supposed to function as a plugin for our host. There may be cases where we would only want one implementation of a particular plug in instead of this articles approach of having multiple plugins or maybe we would want to have priorities assigned to each plug-in. In order to do that, we could put some identifier in the attribute class by which we could sort and filter the plugins to get the one(s) we want. We can also look at the assembly versions. It is probably something we would run into at some point using this technique and using attributes for providing metadata on the plugins is a pretty good solution.

[AttributeUsage(AttributeTargets.Class)]
public class CalculationPlugInAttribute : Attribute
{
    
public CalculationPlugInAttribute(string description)
     {
          m_description = description;
     }

     private string m_description;

     public string Description
    
{
         
get { return m_description; }
         
set { m_description = value; }
    
}
}

So now, when we build a plug-in, we'll make sure to decorate it to explicitly declare the intent of the implementation. This is especially helpful if there are other developers building plugins for our application. In a seperate project we have an implementation of the ICalculator used for adding two numbers together. We'll build this solution, take the resulting dll and drop it in the "Plugins" folder of the host application.

[CalculationPlugInAttribute("This plug-in will add two numbers together")]
class Adder: ICalculator
{
    
#region ICalculator Members

     public int Calculate(int a, int b)
    
{
         
return a + b;
    
}

     public char GetSymbol()
    
{
         
return '+';
    
}

     #endregion

}

Part IV. The Guts

Loading the assemblies from the "Plugins" folder is a straightforward process. We'll find all the dlls in the folder and use Assembly.LoadFile() to add them to a list.

private static List<Assembly> LoadPlugInAssemblies()
{
    
DirectoryInfo dInfo = new DirectoryInfo(Path.Combine(Environment.CurrentDirectory, "Plugins"));
    
FileInfo[] files = dInfo.GetFiles("*.dll");
    
List<Assembly> plugInAssemblyList = new List<Assembly>();

     if (null != files)
    
{
         
foreach (FileInfo file in files)
         
{
              
plugInAssemblyList.Add(
Assembly.LoadFile(file.FullName));
         
}
    
}

     return plugInAssemblyList;

}

Next, we'll take the resulting list and get all the types that implement our ICalculator interface and have the CalculationPlugInAttribute declared. We'll use the Activator class to instantiate an instance of each class we found and return the resulting list of instantiated calculators.

static List<ICalculator> GetPlugIns(List<Assembly> assemblies)
{
     List<Type> availableTypes = new List<Type>();

     foreach (Assembly currentAssembly in assemblies)
          availableTypes.AddRange(currentAssembly.GetTypes());

     // get a list of objects that implement the ICalculator interface AND 
    
// have the CalculationPlugInAttribute
    
List<Type> calculatorList = availableTypes.FindAll(delegate(Type t)
     {
         
List<Type> interfaceTypes = new List<Type>(t.GetInterfaces());
         
object[] arr = t.GetCustomAttributes(typeof(CalculationPlugInAttribute), true);
         
return !(arr == null || arr.Length == 0) && interfaceTypes.Contains(typeof(ICalculator));
     });

     // convert the list of Objects to an instantiated list of ICalculators
   
return calculatorList.ConvertAll<ICalculator>(delegate(Type t) { return Activator.CreateInstance(t) as ICalculator; });

}

Part V. Using Our Plug-In Architecture

I have two projects (a console app and a windows app) implementing the plug in architecture in the code accompanying this project.

The console app is simple and consists of less than a dozen lines:

static void Main(string[] args)
{

     int
         
x = 34,
          y = 56;

     Console.WriteLine(String.Format("x={0} y={1}", x.ToString(), y.ToString()));

     foreach (CalculatorHost calculator in CalculatorHostProvider.Calculators)
     {
          calculator.X = x;
          calculator.Y = y;
         
Console.WriteLine(calculator.ToString());
     }
         
Console.ReadLine();

}

The windows application uses our plugins for the contents of a drop down (bound when the form loads) and is also fairly simple:

private void Form1_Load(object sender, EventArgs e)
{
     m_cbCalculation.DisplayMember =
"Operator";
     m_cbCalculation.DataSource =
CalculatorHostProvider.Calculators;
}

Remember... both of these projects need a subdirectory called "Plugins" to run and you will have to manually drop the implementation of each plugin into this directory for the host application to consume it. Also, nither of these projects are bullet-proof by any means and are demonstration purposes only. We would have to add error handling before they would be production ready. Also, we would probably want to add enough unit tests to our projects to ensure everything is working properly before a distribution build.

Anyways... the important thing is the technique. We could adapt this approach for many differerent types of applications such as creating windows or web services with pluggable functionality or building a mission-critical application architecture where we can plan for future version deployment such that a customer would just have to drop a new dll in a folder in order to avoid application down-time as a result of a new installation process.

I hope you found this article useful.

Until next time,
Happy coding


Login to add your contents and source code to this article
 About the author
 
Matthew Cochran
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
PluggableHostApplication.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
.NET 3.5 Changes by Matthew On September 10, 2007
I forgot to mention that in 3.5 we will have a whole new name space for working with add ins (System.AddIn): http://msdn2.microsoft.com/en-us/arcjournal/bb735304.aspx
Reply | Email | Delete | Modify | 
good job! by Vlad On September 18, 2007
Matt, your article is going to be of major help to me. Please keep submitting - it is always a pleasure reading you.
Reply | Email | Delete | Modify | 
Thanks for your posts! :) by Ralph On September 20, 2007
Sir Matthew, I would just like to thank you for always posting very informative articles. It's always a joy to study through them. They're simple and always straight to the point. I would also like to point out that I appreciate how you always try to update your readers of new features for the .NET framework. Keep up the good work and may you continue to post and share your vast and experienced knowledge about real life, implementable techniques and approaches in .NET. Again sir, thank you very much and God bless. :) Cheers, Ralph
Reply | Email | Delete | Modify | 
Introduction? by Rami On October 3, 2007
Great Article Matt! The subject for this is "Introduction to...", Will there be more on this? or the "Introduction" is it?
Reply | Email | Delete | Modify | 
Re: Introduction? by Matthew On October 12, 2007

If there's enough interest, I could drill in a bit with another article.

Reply | Email | Delete | Modify | 
Nice Article by Mohammad On October 31, 2007
But i want to ask if there are Security Issues needed to load DLLs
Reply | Email | Delete | Modify | 
Doubt in Plugin by Srinivasan On December 21, 2007
I want to know, by using Plugin Architecture, can we change the existing UI of Windows Application like adding another Form / usercontrol / controls in the existing Form, etc.
Reply | Email | Delete | Modify | 
Re: Doubt in Plugin by Matthew On January 17, 2008
Definately,  you just have to architect the solution appropriately.  You could load modules that would appear as drop down lists in the menubar and put all the required forms in the dll you are making into a plug-in.
Reply | Email | Delete | Modify | 
Good Stuff Matt by Muhammad On October 24, 2008
Cool Matt, really cool good stuff, interesting topic and very helpful. Never too late to mark good helpful topics
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.