Click here to Skip to main content
6,291,522 members and growing! (13,128 online)
Email Password   helpLost your password?
Languages » C# » General     Intermediate

Plugin Architecture using C#

By Shoki

How to make plugins to work with .NET
C#.NET 1.0, Win2K, WinXP, Win2003, Dev
Posted:3 Aug 2003
Views:155,238
Bookmarked:152 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
53 votes for this article.
Popularity: 6.54 Rating: 3.79 out of 5
3 votes, 5.7%
1
4 votes, 7.5%
2
6 votes, 11.3%
3
15 votes, 28.3%
4
25 votes, 47.2%
5

Sample Image - Plugins.jpg

Introduction

This article demonstrates to you how to incorporate a single module, as a plugin for another application or use it as a standalone application. The article will demonstrate how a minimal change is required to obtain the above result.

Background

The basic idea for this article has been adopted from the net, I don't remember the original author, but I found the code as a console application, while what I was searching was a method to use one of my windows application module in another application and run it standalone as well with as minimal changes a possible. A little changes to the console application, and this article is what the final result looks like.

Using the code

The key to a plugin architecture is the implementation of a minimal set of methods by the plugins. These methods are used by the main (incorporating) application to find and recognize the plugins. This minimal set of method is achieved by making an interface, which would declare the methods, that are to be implemented by the plugins. This interface has been defined as follows:

public interface IPlugin
{
    string Name{get;set;}
    IPluginHost Host{get;set;}
    void Show();
}

The interface define a few methods. Name is used to get the name of the plugin to be shown on the main application in the menu. IPluginHost is used to let the plugin know who is hosting the plugin. Show will show the main form of the plugin application.

We now make our first plugin in form of a windows application like this.

using System;
using PlugIn;

namespace Dynamic
{
    class PlugIn : IPlugin
    {
        private string m_strName;
        private IPluginHost m_Host;
        
        public PlugIn()
        {
            m_strName = "Dynamic"; 
        }
        
        public string Name
        {
            get{return m_strName;}
            set{m_strName=value;}
        }
        
        public void Show()
        { 
            Main1 mn = new Main1();
            mn.ShowDialog();
        }

        public IPluginHost Host
        {
            get{return m_Host;}
            set
            {
                m_Host=value;
                m_Host.Register(this);
            }
        }
    }
}

public class Main1 : System.Windows.Forms.Form 
{ 
    //Your original code goes here...


    [STAThread]
    static void Main() 
    {
        Application.Run(new Main1());
    }
}

The above code declare the a plugin class so that the parent application could recognize it as a plugin. The application also declare a form class, which is the startup form.

Now compile the plugin as an executable file. Run it, it should run as a normal standalone exe. Copy the exe into the main applications executable directory, and rename it as a DLL instead of a exe.

Now we move to our main application:

for that we have to interface, which is implemented by our application so that it registers with the plugins.

    public interface IPluginHost
    {
        bool Register(IPlugin ipi);
    }

The main application is implemented as windows form.

public class Form1 : System.Windows.Forms.Form, IPluginHost 
{
    private System.Windows.Forms.MainMenu mainMenu1;
    private System.Windows.Forms.MenuItem menuItem1; private IPlugin[] ipi;

    private void Form1_Load(object sender, System.EventArgs e)
    {
        string path = Application.StartupPath;
        string[] pluginFiles = Directory.GetFiles(path, "*.DLL");
        ipi = new IPlugin[pluginFiles.Length];

        for(int i= 0; i<pluginFiles.Length; i++)
        {
            string args = pluginFiles[i].Substring(
                pluginFiles[i].LastIndexOf("\\")+1,
                pluginFiles[i].IndexOf(".DLL")-
                pluginFiles[i].LastIndexOf("\\")-1);

            Type ObjType = null;
            try
            {
                // load it
                Assembly ass = null;
                ass = Assembly.Load(args);
                if (ass != null)
                {
                    ObjType = ass.GetType(args+".PlugIn");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            try
            {
                // OK Lets create the object as we have the Report Type
                if (ObjType != null)
                {
                    ipi[i] = (IPlugin)Activator.CreateInstance(ObjType);
                    ipi[i].Host = this;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }

}

In OnLoad(), we check for all the DLLs present in the application directory, and scan if any implement the plugin interface. If it does we store it and register the plugin with us. This plugin in turn calls the register method on the main application. The register method add the plugin name with out menu.

        public bool Register(IPlugin ipi)
        {
            MenuItem mn = new MenuItem(ipi.Name,new EventHandler(NewLoad));

            Console.WriteLine("Registered: " + ipi.Name);
            menuItem1.MenuItems.Add(mn);
            return true;
        }        

The next time the plugin menu is click, we check for the respective plugin name and call the appropriate plugin.

private void NewLoad(object sender, System.EventArgs e) {
    
    MenuItem mn = (MenuItem)sender; for(int

    i=0; i < ipi.Length; i++)
    {
        string strType = mn.Text;
        if(ipi[i]!=null)
        {
            if(ipi[i].Name==strType)
            {
                ipi[i].Show();
                break;
            }
        }
    }            
}    
        

Now compile and run the application, with the plugin DLL in the application path, the plugin name would show in the menu. Click the menu and the plugin pops up. Hope you find the code useful.

History

  • This is the initial release 1.0.0R.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Shoki


Member

Occupation: Team Leader
Location: India India

Other popular C# articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 31 (Total in Forum: 31) (Refresh)FirstPrevNext
GeneralWhy use IPluginHost Pinmembernulkoud2:41 16 Jun '09  
GeneralCast Pinmemberassismvla11:13 19 Apr '09  
GeneralRe: Cast PinmemberManadar4:25 14 May '09  
GeneralConvert to VB.net PinmemberMichalss23:49 28 Mar '09  
GeneralProof read proof read proof read!!!!! Pinmemberhavyck11:08 5 Apr '07  
GeneralRe: Proof read proof read proof read!!!!! Pinmemberjustapgmr6:23 14 Jan '09  
GeneralRe: Proof read proof read proof read!!!!! Pinmemberwibblewoo2:22 28 Jan '09  
GeneralA little bit code optimization PinmemberAlexander M. Batishchev1:13 11 Apr '06  
GeneralRe: A little bit code optimization PinmemberAlexander M. Batishchev13:47 11 Apr '06  
GeneralRe: A little bit code optimization PinmemberDavid30018:48 9 Dec '06  
GeneralRe: A little bit code optimization PinmemberAlexander M. Batishchev5:21 3 Apr '07  
GeneralRe: A little bit code optimization PinmemberHenk Burgstra16:21 4 Aug '07  
GeneralRe: A little bit code optimization PinmemberBZZR20:49 14 Nov '07  
Generalother directory than app path?? PinmemberBadscher0:42 15 Feb '06  
AnswerRe: other directory than app path?? PinmemberAlexander M. Batishchev2:15 12 Apr '06  
GeneralReflection in VB2005 Pinmemberhrgy848:53 6 Jan '06  
GeneralSecurity concerns PinmemberBiju P K1:13 17 May '05  
GeneralRe: Security concerns PinmemberValer BOCAN3:44 26 Sep '05  
GeneralRe: Security concerns PinmemberMrOzark20:07 16 Oct '05  
GeneralRe: Security concerns PinmemberJerod Edward Moemeka8:12 8 Jun '06  
GeneralChild Forms Pinmemberirungu1:22 4 May '05  
GeneralPerformance of this Plugin Architecture Pinmembersend2tusharp@yahoo.com2:27 11 Aug '04  
GeneralImplemention Problem with Pocket PC application. Pinmemberkirankumart19:40 10 Jul '04  
GeneralRe: Implemention Problem with Pocket PC application. Pinmemberieb@mac.com1:18 12 Jun '07  
GeneralGood start, more resources here... Pinmembercharleswoerner12:00 28 Apr '04  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 3 Aug 2003
Editor: Nishant Sivakumar
Copyright 2003 by Shoki
Everything else Copyright © CodeProject, 1999-2009
Web16 | Advertise on the Code Project