Implementing a Plug-In Architecture in C#

How to implement a plug-in architecture in C# using reflection and run-time inspection of type information.


January 01, 2003
URL:http://www.drdobbs.com/cpp/implementing-a-plug-in-architecture-in-c/184403942

Introduction

C#, in concert with the underlying .NET platform, provides some powerful features and constructs. Some of what is offered is new, and some is the sincerest form of flattery to the platforms and languages that have come before it. However, the unique combination of features provides some interesting ways to achieve project goals. This article discusses some of the features that can be used to design extensible solutions with the use of plug-ins. It also examines a skeleton example that has the potential to replace the stand-alone applications that are found in many organizations. An organization’s application suite usually consists of many targeted solutions to manage data. One application might exist for managing employee information, and another might target customer relationships. Often solutions of this nature are designed as stand-alone applications with little interaction and some duplication of effort. As an alternative, these solutions can be designed as plug-ins that are hosted by a single application. A plug-in design helps to share common functionality between solutions and also provides a common look and feel.

Figure 1 shows a screenshot of the example application. The user interface is similar to many other familiar applications. The window is divided vertically into two panes. The left pane is a tree view used for displaying the list of plug-ins. Under each plug-in branch are branches for the data on which the plug-in operates. The right pane is used for editing plug-in data after it is selected in the tree view. The individual plug-ins provide the user interface for editing the data they contain. It also shows a workspace that might be used by a talent agent. The agent needs to manage his comedic talent and the clubs that they perform in.

Figure 1: The example application

The Big Picture

At the highest level of abstraction, the host application must be able to load plug-ins and then communicate with plug-ins to take advantage of their designed services. Both of these tasks can be implemented in different ways depending on a developer’s choice of language and platform. If the choice is C# and .NET, then reflection can be used for loading plug-ins, and interfaces or abstract classes can be used as a means for generic communication.

To help conceptualize the communication that occurs between a host application and a plug-in, the Strategy design pattern can be applied. For the uninitiated, Erich Gamma originally offered design patterns [1]. Design patterns help to communicate commonly used architectures and object strategies. The premise is that while projects differ in their inputs and outputs they are for the most part similar in structure. Design patterns help developers utilize proven object strategies to solve new problems. They can also become the de facto language that developers use to discuss solutions without intimate knowledge of the problem to be solved, or the specific language constructs that will be used. The gist of the Strategy design pattern is to decouple the functionality of a solution from its container. This decoupling is achieved by separating the implementation of the host application and the things it must do into strategies. Communication between the host application and its strategies is then done through a well-defined interface. This separation provides two immediate benefits. First, anytime a software project can be broken down into smaller discrete units, it is a bonus to the engineering process. Smaller code pieces are easier to build and maintain. The second benefit is the ability to switch strategies without affecting the operation of the host application. The host application is not concerned with specific strategies, just the common mechanism to communicate with the strategies.

Creating the Interface

In C#, an interface defines what a class is expected to support. The expectation that an interface defines is a collection of signatures for methods, properties, and events. To use an interface, a concrete class must be defined that implements the interface by defining what each signature does. Listing 1 shows the interface, IPlug, defined in the example application.

Listing 1: The IPlug interface

public interface IPlug
{
  IPlugData[] GetData();
  PlugDataEditControl GetEditControl(IPlugData Data);
  bool Save(string Path);
  bool Print(PrintDocument Document);
}

The interface defines four methods: GetData, GetEditControl, Save, and Print. These four method definitions do not define any implementation, but they guarantee that any class that supports the IPlug interface will support the method calls.

Custom Attributes

Before examining any more code, the discussion must turn to custom attributes. Custom attributes are one of the exciting new features that .NET developers can utilize. Attributes are a common construct to all programming languages. For example, the access specifier of a method (public, private, or protected) is an attribute of that method. Custom attributes are exciting because .NET developers are no longer restricted to the set of attributes designed into their programming language of choice. A custom attribute is a class that is derived from System.Attribute and allows the code you write to be self-describing. Custom attributes can be applied to most language constructs in C# including classes, methods, events, fields, and properties. The example code defines two custom attributes, PlugDisplayNameAttribute and PlugDescriptionAttribute, that all plug-ins must support at the class level. Listing 2 is the class definition for PlugDisplayNameAttribute. This attribute is used by the host application as the text to display for the plug-in’s tree node. During execution, the host application is able to query the value of attributes by using reflection.

Listing 2: The PlugDisplayNameAttribute class definition

[AttributeUsage(AttributeTargets.Class)]
public class PlugDisplayNameAttribute : System.Attribute
{
  private string _displayName;

  public PlugDisplayNameAttribute(string DisplayName) : base()
  {
    _displayName=DisplayName;
    return;
  }

  public override string ToString()
  {
    return _displayName;
  }

Plug-Ins

The example application contains two plug-in implementations. The plug-ins are defined in EmployeePlug.cs and CustomerPlug.cs. Listing 3 shows a partial listing of the class definition for EmployeePlug.

Listing 3: A partial listing of the EmployeePlug class definition

[PlugDisplayName("Employees")]
[PlugDescription("This plug is for managing employee data")]
public class EmployeePlug : System.Object, IPlug
{
  public IPlugData[] GetData()
  {
     IPlugData[] data = new EmployeeData[]
      {
        new EmployeeData("Jerry", "Seinfeld")
        ,new EmployeeData("Bill", "Cosby")
        ,new EmployeeData("Martin", "Lawrence")
      };

    return data;
  }

  public PlugDataEditControl GetEditControl(IPlugData Data)
  {
    return new EmployeeControl((EmployeeData)Data);
  }

  public bool Save(string Path)
  {
    //implementation not shown
  }

  public bool Print(PrintDocument Document)
  {
    //implementation not shown
  }
}

Some points of interest include:

  1. The class implements the IPlug interface. This is important because by design the host application has no direct knowledge of any specific plug-in class definition. It communicates with all plug-ins using the definition of the IPlug interface. This design utilizes the object-oriented principle of polymorphism. Polymorphism allows for the communication with a type to occur with a reference to one of its base types or an interface that the type supports.
  2. The class is marked with the two attributes required by the host application to be considered a valid plug-in. In C#, to assign an attribute to a class, you declare an instance of the attribute enclosed in brackets before the class definition.
  3. In an effort to be brief and focused, the class is using hard-coded data. In a production plug-in, the data would be persisted in a database or file. Each plug-in is ultimately responsible for the management of the data it contains. The data for EmployeePlug is stored as objects of type EmployeeData, which is a concrete class that supports the interface IPlugData. The IPlugData interface is defined in IPlugData.cs and provides a lowest common denominator for data exchange between the host application and any of its plug-ins. Objects that support the IPlugData interface provide notification when the underlying data changes. The notification comes in the form of the DataChanged event.
  4. When the host application needs to display a list of the data a plug-in contains, it calls the GetData method. The method returns an array of IPlugData objects. The host application can then call the ToString method of each object in the array to use as the text for a tree node. The ToString method is overridden in the EmployeeData class to display an employee’s full name.
  5. The IPlug interface defines a Save method and a Print method. The purpose of the two methods is to notify a plug-in when it should print and save its data. The EmployeePlug class is responsible for providing an implementation for printing and saving its data. In the case of the Save method, the path to save the data in is provided within the method call. This presumes that the host application will query the user for the path information. The querying of path information is a service that the host application supplies to each of its plug-ins, saving the plug-ins from having to query the user itself. For the Print method, the host application passes in a System.Drawing.Printing.PrintDocument instance that contains the selected printing options. In both cases, the interaction with the user is consistent as provided by the host application.

Reflection

With a plug-in defined, the next step is to examine the code in the host application that loads plug-ins. To do this, the host application uses reflection. Reflection is a feature in .NET that allows for the run-time inspection of type information. With the aid of reflection, types are loaded and inspected. The inspection discerns if the type can be used as a plug-in. If a type passes the tests for a plug-in, it is added to the host application’s display and becomes accessible to users.

The example application uses three framework classes for its reflection work: System.Reflection.Assembly, System.Type, and System.Activator.

The System.Reflection.Assembly class represents a .NET assembly. In .NET, the assembly is the unit of deployment. For a typical Windows application, the assembly is deployed as a single Win32 portable executable file, with additional information to enable the .NET runtime. Assemblies can also be deployed as Win32 DLLs (dynamic link libraries), with additional .NET runtime information. The System.Reflection.Assembly class can be used at run time to get information about the executing assembly or any other assembly accessible to the executing assembly. The available information includes the types that the assembly contains.

The System.Type class represents a type declaration. A type declaration could be a class, interface, array, structure, or enumeration. After being instantiated with a type, the System.Type class can be used to enumerate supported methods, properties, events, and interfaces of the type.

The System.Activator class can be used to create an instance of a type.

Loading Plug-Ins

Listing 4 contains the method LoadPlugs. LoadPlugs is located in HostForm.cs and is a private instance method of the HostForm class. The LoadPlugs method uses .NET reflection to load the available plug-in files, validates them as plug-ins that can be used by the host application, and then adds them to the host application’s tree view. The method goes through several steps:

  1. By using the System.IO.Directory class, the code is able to do a wildcard search for all of the files with a matching .plug file extension. The Directory class’ static method GetFiles returns an array of System.String that contains the absolute path of each file in the hard-coded path that matches the pattern.
  2. After retrieving the array, the method next iterates through each file path attempting to load the file into a System.Reflection.Assembly instance. The code that attempts to create an Assembly instance is wrapped in a try block. If the file is not a valid .NET assembly, then an exception is caught and feedback in the form of a message box is provided to the user about the unsuccessful attempt. If more file paths are left to process, the loop is able to continue.
  3. With an assembly loaded, the code next iterates through each accessible type in the assembly to see if it supports the HostCommon.IPlug interface.
  4. If the type supports HostCommon.IPlug, the code next validates that the type also supports the attributes that have been defined for plug-ins. If any of the attributes are not supported, a HostCommon.PlugNotValidException is thrown. After the exception is thrown, it is caught and feedback in the form of a message box is provided to the user explaining why the plug-in failed. If more file paths are left to process, the loop is able to continue.
  5. Finally, if the type supports HostCommon.IPlug and defines all of the required attributes, it is wrapped in an instance of PlugTreeNode. The PlugTreeNode instance is then added to the host application’s tree view.

Listing 4: The method LoadPlugs


private void LoadPlugs()
{
  string[] files = Directory.GetFiles("Plugs", "*.plug");

  foreach(string f in files)
  {

    try
    {
      Assembly a = Assembly.LoadFrom(f);
      System.Type[] types = a.GetTypes();
      foreach(System.Type type in types)
      {
        if(type.GetInterface("IPlug")!=null)
        {
          if(type.GetCustomAttributes(typeof(PlugDisplayNameAttribute),
  false).Length!=1)
            throw new PlugNotValidException(type,
              "PlugDisplayNameAttribute is not supported");
          if(type.GetCustomAttributes(typeof(PlugDescriptionAttribute),
  false).Length!=1)
            throw new PlugNotValidException(type, 
              "PlugDescriptionAttribute is not supported");

          _tree.Nodes.Add(new PlugTreeNode(type));
        }
      }
    }
    catch(Exception e)

    {
      MessageBox.Show(e.Message);
    }
  }

  return;
}

Deployment

The primary framework for the example application is deployed as two assemblies. The first assembly is Host.exe, and it houses the window forms host application. The second assembly is HostCommon.dll, and it houses all of the types that are used for communication between the host application and plug-ins. For example, the IPlug interface is deployed in HostCommon.dll so that it is equally accessible to both the host application and plug-ins. With the two assemblies in place, additional assemblies can be deployed that store the individual plug-ins. These assemblies are deployed to the plugs directory directly below the application path. The EmployeePlug class is deployed in the Employee.plug assembly, and the CustomerPlug class is deployed in the Customer.plug assembly. The example has taken the liberty of creating its own .plug file extension for plug-ins. The plug-in assemblies that are deployed are ordinary .NET library assemblies. Usually library assemblies are deployed with a .dll extension. The special extension has no influence on the runtime, but helps the plug-ins to stand out to users.

Alternative Designs

The design chosen for the example application is not exclusively correct. For example, using attributes is not required to develop a plug-in solution with C#. The services provided by the two defined attributes could also be provided by two property signatures added to the IPlug interface definition. Attributes were chosen because the name of a plug-in and its description are declarative in nature and fit quite nicely into the attribute model. Of course, using attributes requires more reflection code in the host application. This is a case-by-case design decision that developers will have to make on their own.

Conclusion

The example application is intended to be as thin as possible to help accentuate the communication between a host application and plug-ins. For a production environment, many improvements can be made to make a more useful solution. Some possible additions include:

  1. Increasing the communication points between the host and the plug-in by adding more method, property, and event signatures to the IPlug interface. Additional interaction between the host and plug-ins will allow for plug-ins that can do more things.
  2. Enabling users to explicitly select the plug-ins that are loaded.

Source Code

The complete source code for the sample application is available for download in walchesk.zip.

Notes

[1] Erich Gamma et al. Design Patterns (Addison-Wesley, 1995).


Shawn Patrick Walcheske is a software developer in Phoenix, Arizona. He is a Microsoft Certified Solution Developer and a Sun Certified Programmer for the Java 2 Platform.

Terms of Service | Privacy Statement | Copyright © 2024 UBM Tech, All rights reserved.