c# - 为内部范围代码实现插件实例属性
我已经为我的一个程序创建了自己的插件架构。
基本上 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 的实例。
我知道单例似乎不是执行此操作的正确方法,但我无法提供其他解决方案。也许多吨可以解决这个问题,但我不希望我的插件编写者一直这样做,
Plugin.Instance["PluginB"]
这似乎无关紧要。
感谢您的任何帮助。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如建议的,您应该将它们存储在某种列表中,可能在托管应用程序中,也可能在库中。
您已经有了对当前插件的引用,使用“this”关键字,只需通过构造函数或方法将其传递到其他类中即可:
例如
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
删除
static
关键字并保留List
来循环它们。Remove the
static
keyword and keep aList<Plugin>
to loop over them.