Implementing a plug-in architecture with C #

Source: Internet
Author: User

ByShawn Patrick walcheske

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 ages 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 your organizations. an organization's application suite usually consists of specified 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: The example application

Figure 1 shows a screenshot of the example application. the user interface is similar to your 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. figure 1 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.

The big picture

At the highest level of each action, 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 patterns1. design patterns help to communicate commonly used ubuntures 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 mechanic 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: The iplug Interface

Public interface iplug
{
Iplugdata [] getdata ();
Plugdataeditcontrol geteditcontrol (iplugdata data );
Bool save (string path );
Bool print (printdocument document );
}

Listing 1 shows the interface,Iplug, Defined in the example application. The interface defines four methods:Getdata,Geteditcontrol,Save, AndPrint. These four method definitions do not define any implementation, but they guarantee that any class that supportsIplugInterface will support the method CILS.

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 ages. for example, the access specifier of a method (Public,Private, OrProtected) 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 fromSystem. AttributeAnd 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,PlugdisplaynameattributeAndPlugdescriptionattribute, That all plug-ins must support at the class level.

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;
}
}

Listing 2 is the class definitionPlugdisplaynameattribute. 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.

Plug-ins

The example application contains two plug-in implementations. The plug-ins are defined inEmployeeplug. CSAndCustomerplug. CS.

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
}
}

Listing 3 shows a partial listing of the class definitionEmployeeplug. Some points of interest include:

  1. The class implementsIplugInterface. 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 ofIplugInterface. 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 wocould be persisted in a database or file. each plug-in is ultimately responsible for the management of the data it contains. the dataEmployeeplugIs stored as objects of TypeEmployeedata, Which is a concrete class that supports the interfaceIplugdata.IplugdataInterface is defined inIplugdata. CSAnd provides a lowest common denominator for data exchange between the host application and any of its plug-ins. objects that supportIplugdataInterface provide notification when the underlying data changes. The notification comes in the form ofDatachangedEvent.
  4. When the host application needs to display a list of the data a plug-in contains, it calltheGetdataMethod. The method returns an arrayIplugdataObjects. The host application can then callTostringMethod of each object in the array to use as the text for a tree node.TostringMethod is overridden inEmployeedataClass to display an employee's full name.
  5. TheIplugInterface definesSaveMethod andPrintMethod. The purpose of the two methods is to operate y a plug-in when it shocould print and save its data.EmployeeplugClass is responsible for providing an implementation for printing and saving its data. In the case ofSaveMethod, 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. forPrintMethod, the host application passes inSystem. Drawing. Printing. printdocumentInstance 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, AndSystem. Activator.

TheSystem. reflection. AssemblyClass represents. 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. net runtime. assemblies can also be deployed as Win32 DLLs (dynamic link libraries), with additional. net runtime information. theSystem. reflection. AssemblyClass 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 should des the types that the Assembly contains.

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

TheSystem. ActivatorClass can be used to create an instance of a type.

Loading plug-ins
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;
}

Listing 4 contains the MethodLoadplugs.LoadplugsIs located inHostform. CSAnd is a private instance method ofHostformClass.LoadplugsMethod 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 usingSystem. Io. DirectoryClass, the code is able to do a wildcard search for all of the files with a matching. PlugFile extension.DirectoryClass 'static MethodGetfilesReturns an arraySystem. StringThat 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 intoSystem. reflection. AssemblyInstance. The code that attempts to createAssemblyInstance 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 supportsHostcommon. iplugInterface.
  4. If the type supportsHostcommon. 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,Hostcommon. plugnotvalidexceptionIs 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 supportsHostcommon. iplugAnd defines all of the required attributes, It is wrapped in an instancePlugtreenode.PlugtreenodeInstance is then added to the Host application's Tree View.
Deployment

The primary framework for the example application is deployed as two assemblies. The first assembly isHost.exe, And it houses the window forms Host application. The second assembly isHostcommon. 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 inHostcommon. dllSo 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. theEmployeeplugClass is deployed inEmployee. PlugAssembly, andCustomerplugClass is deployed inCustomer. PlugAssembly. The example has taken the liberty of creating its own. PlugFile Extension for plug-ins. The plug-in assemblies that are deployed are ordinary. Net Library assemblies. Usually library assemblies are deployed with. DllExtension. 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 cocould also be provided by two Property signatures added toIplugInterface 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 demo-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, cannot 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 toIplugInterface. 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.

Note

[1] Erich Gamma et al. design patterns (Addison-Wesley, 1995 ).

About the author

Shawn Patrick walcheskeIs a software developer in Phoenix, Arizona. He is a Microsoft certified Solution Developer and a Sun Certified programmer for the Java 2 platform. He can be contacted at questions@walcheske.com.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.