【问题标题】:c# - Implementing plugin Instance property for internal scoped codec# - 为内部范围代码实现插件实例属性
【发布时间】:2010-11-12 14:52:16
【问题描述】:

我已经为我的一个程序创建了自己的插件架构。

基本上 Plugin 是我所有插件的基类,并说我有 PluginA : Plugin、PluginB : Plugin 之类的插件。

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

现在像往常一样,我的每个插件都有其他东西,例如表单和其他类。我想从那些类中访问当前的插​​件实例;

Plugin.Instance.Settings()

如果我确实在插件 ctor 中分​​配 _instance 字段,例如;

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

然后对于每个加载的插件,实例都会被覆盖,我会得到奇怪的结果,比如 PluginB.Instance 返回一个 PluginA 的实例。

我知道单例似乎不是这样做的正确方法,但我无法提供其他解决方案。也许 multiton 可以解决这个问题,但我不希望我的插件编写者去

Plugin.Instance["PluginB"] 

似乎无关紧要的所有时间。

感谢您的帮助。

【问题讨论】:

    标签: c# plugins singleton instance multiton


    【解决方案1】:

    按照建议,您应该将它们存储在某种列表中,可能在托管应用程序中,也可能在库中。

    您已经有了对当前插件的引用,使用 'this' 关键字,只需通过构造函数或方法将 this 传递给您的其他类:

    喜欢

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

    【讨论】:

    • 是的,这是一种解决方案,但该方法的问题是——让我解释一下;我有一个名为 LibEvents 的插件,它从 xml 源读取一些事件,它包含很多条目。我认为传递所有插件实例虽然这些事件是无意义的,并且从插件开发人员的角度来看可能会使事情变得复杂。
    【解决方案2】:

    删除 static 关键字并保留 List<Plugin> 以循环它们。

    【讨论】:

    • 我不希望插件看到彼此的实例。
    • 并且我删除了 static 关键字,插件助手类将无法访问它。
    猜你喜欢
    • 2019-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-22
    • 1970-01-01
    相关资源
    最近更新 更多