Use C # And the. NET Framework to develop your own plugin Architecture

Source: Internet
Author: User

Takeaway:Using Dynamic applications allow third parties to create plugins that extend the functionality of the application. zach smith explains how developers can leverage. net Framework and C # To easily create a plugin architecture of their own. A sample solution is also provided that demonstrates the concepts described.

This article is also available as a techrepublic download.

In the enterprise world you rarely come into SS any in-house application that will allow plugins to be written and imported without any changes to core application code. I believe one of the reasons for this is that in the past it was difficult to implement the type of architecture that will allow the use of plugins.

Developers were forced to either spend a large amount of time on the architecture design, or figure out a work around to accomplish their goals. as we all know, large amounts of time are not easy to come by in the enterprise world, and it seems most developers were forced to develop workarounds. microsoft has solved this issue with C # And. net Framework. it is now trivial to develop an application that will allow components to be plugged-in dynamically, without any core code changes.

The solution has ded with this article (see the project files found in the download) demonstrates how to implement a simple plugin architecture. this demonstration solution dynamically executes tests (each test is a plugin) and reports the results. each test is able to do something different, and tests shocould be able to be added or removed without any changes to the core test engine functionality. this allows us to add tests to the application without rebuilding the entire application. I have called this solution "systemtests", and it contains four projects:Sharedobjects,Testengine,Testexamples, AndTestapplication.

Applications that allow plugins have just a few basic layers that enable the Plugin Functionality, andSystemtestsSolution is no different.

The shared objects Layer

The shared objects layer is responsible for providing a way for the main application to communicate with the Plugins. Both the main application and the Plugins reference the shared objects.

The shared objects layer is implemented bySharedobjectProject. This project contains the following items:

  • Itest. CS-This is an interface that controls how the core application will communicate with the Plugins. In this interface you will find the following methods and properties:

    • Methods:

      • Execute (Testenginestate)-Executes the test.
    • Properties:
      • Result-ReturnsTestresultObject that holds information about the result of a test.
      • ID-Holds the ID of the test.
      • Name-Holds the name of the test.
      • Description-Holds the description of the test.
  • Test. CS-This is a base class that contains very little functionality. this class is a helper class that each test inherits from. after inheriting from this class, the developer writing the test does not have to explicitly write the properties needed to implement the itest interface.
  • Testenginestate. CS-This class is passed to every test and allows the tests to determine which tests have passed or failed previusly. Using this class you can make tests be dependent on one another.
  • Testresult. CS-When a test has finished executing, it populates itsResultProperty withTestresultObject. This class contains several properties that allow the test engine to determine the results of the test:
    • Properties:

      • Message-This property can contain in a message why the test passed or failed.
      • Passed-This is a boolean property that indicates whether or not the test passed. If the test passed, this property will be set to true.
The core or Main Application Layer

The main application layer is where the core functionality for the application is implemented. This layer ties all of the Plugins together, does any reporting that is needed, and interfaces with the user or database.

The main application layer is implemented byTestengineProject, which contains one class-"engine". It is the job ofEngineClass to gather the tests that must be ran and run them, reporting the results back to the calling application throughTestenginestateObject.

The two most important methods in the engine class areLoadconfigurationAndCreatetest. These two methods are explained in detail below:

  • Loadconfiguration
    Determines which plugins must be loaded by parsing an xml configuration file.LoadconfigurationIs implemented with the code inListing, Commented here to explain what is happening:
Listing

Privatevoid loadconfiguration (string path)
{
Xmldocument configuration = newxmldocument ();
// Load the given XML file into our XML document.
Configuration. Load (PATH );

// Get a nodelist of the Test Nodes.
Xmlnodelist tests = configuration. selectnodes ("/testengine/tests/test ");

// Loop through the Test Nodes and load each test.
Foreach (xmlnode test in tests)
{
// Load the enabled attribute to determine if the test is enabled.
Xmlattribute enabled = test. attributes ["enabled"];

If (enabled. value. tolower () = "true ")
{
Xmlattribute assemblypath = test. attributes ["assembly"];
Xmlattribute typename = test. attributes ["type"];

// Call createtest to instantiate the test and add it to
// Tests property.
This. Tests. Add (createtest (assemblypath. Value, typename. Value ));
}
}
}

  • Createtest
    CreatesItestObject from the given assembly path and type name. This method is shown inListing BWith Comments to describe the steps required to dynamically instantiate an object from an assembly:
Listing B

Privateitest createtest (string assemblypath, string typename)
{
// Create an objecthandle object that will hold an instance of the requested
// Type in the given assembly. The objecthandle class is in
// System. remoting namespace.
Objecthandle handle = activator. createinstancefrom (assemblypath, typename );

// Unwrap the object instance into an object class.
Object test = handle. Unwrap ();

// Test to make sure the object implements the itest interface. Any object
// That does not implement the itest interface will cause an exception
// Be thrown.
If (test isitest)
Return (itest) test; // return the object as an itest instance.
Else
Thrownewexception ("this type does not implement itest, Which is required./nassembly:" + assemblypath + "/ntype:" + typename );
}

The plugin Layer

The plugin layer contains the plugins that are setup for the application. generally, each plugin contained in this layer will implement one or more interfaces from the shared objects layer. this allows the main application layer to communicate with the Plugins.

The plugin layer is implemented byTestexamplesProject. The functionality within each test can vary from one test to another, and there are no rules on what a test has to do. The only rule is that the test must implementItestInterface, everything else is up to the test developer.

Listing cIs an example of a very simple test, called "mathtest". This test passes if 1 does not equal 2 (1! = 2), and fails if 1 equals 2 (1 = 2 ):

Listing c

Using system;
Using system. Collections. Generic;
Using system. text;
Using systemtests. Export dobjects;

Namespace systemtests. testexamples
{
Publicclassmathtest: Test, itest
{
Publicoverrisponid execute (testenginestate state)
{
// Set the ID for this test.
This. ID = "mathtest ";
// Set the name of this test.
This. Name = "math test ";
// Set the description of this test.
This. Description = "tests to see if 1 = 2 ";

// Instantiate a testresult object to hold
// Results of this test.
Testresult result = newtestresult ();

// Very simple test to see if 1 = 2
If (1 = 2)
Result. Passed = true;
Else
Result. Passed = false;

// Set the result.
This. Result = result;
}
}
}

While this test is extremely simple, as I mentioned abve it cocould do anything as long as it implementsItestInterface.

The specified ded solution contains two other sample tests:

  • Supermantest-Determines whether or not the Superman class implementsIsuperheroInterface.
  • Webtest-Determines whether or not http://microsoft.com can be accessed from the Local Computer (this may fail if you're behind a proxy ).

There is one more project in the solution already ded with this article called "testapplication". This project is a very simple windows form application that displays results fromTestengine.

Apply to your situation

Take a look at the solution into ded with this articleand think about how this type of Plugin Functionality cocould be applied to business problems at your company. chances are there are at least a couple instances where this type of highly dynamic functionality cocould be very helpful. feel free to use the code examples for your own use!

 

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.