سؤال

i've created my own plugin architecture for one of my programs.

Basicly Plugin is the base class for all of my plugins and say that i've plugins like PluginA : Plugin, PluginB : Plugin.

public class Plugin 
{
    private static Plugin _instance;
    public static Plugin Instance { get { return Plugin._instance; } }
}

Now as usual each of my plugins have other stuff like forms and other classes. From that classes i want to access the current plugin instance like;

Plugin.Instance.Settings()

If i do assign _instance field in plugin ctor like;

public Plugin(GlobalSettings gs, PluginSettings ps)
{
    Plugin._instance=this;
}

Then for each loaded plugin the Instance is overwritten and i get strange results like PluginB.Instance returning an instance of PluginA.

I know singleton does not seem the quite right way to do this, but i wasn't be able to come with another solution. Maybe a multiton can solve this, but i don't want my plugin writers to go for

Plugin.Instance["PluginB"] 

all time which seems irrelevant.

Thanks for any help.

هل كانت مفيدة؟

المحلول

As suggested, you should store these in a List of some sort, possibly in the hosting application or possibly in the library.

You already have a reference to the current plugin, with the 'this' keyword, simply pass this into your other classes via constructor or methods :

like

public class MyPlugin :Plugin
{
    private MyClass myClass;

    public MyPlugin()
    {
         this.myClass = new MyClass(this);  
         this.myClass.DoSomething();
    }
    public void Something()
    {
         //Called back into from MyClass

    }
}
public class Myclass
{
     public Plugin OwnerPlugin {get;internal set;}
     public MyClass(Plugin ownerPlugin)
     {
           this.OwnerPlugin = ownerPlugin;
     }
     public void DoSomething()
     {
          //do something with ownerplugin
          this.OwnerPlugin.Something();
     } 
}

نصائح أخرى

Remove the static keyword and keep a List<Plugin> to loop over them.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top