MEF:导入的字段值未更新
我正在尝试将一个名为“设置”的字段从主窗体导出到插件,如下面的代码所示。我正在使用名为 CreateSettings() 的主表单函数来更新私有 _settings 字段。但是,当我这样做时,导入的插件设置永远不会改变,并且始终是原始初始化值“defaultname”和“defaultpass”。我不知道发生了什么事?
主窗体:
public partial class Form1 : Form
{
[Export(typeof(ISettings))]
private Settings _settings = new Settings("defaultname", "defaultpass");
private void CreateSettings(name, password)
{
_settings = new Settings(name, password);
}
}
插件控件:
[Export(typeof(IPlugin))]
public partial class MyPlugin : UserControl, IPlugin
{
[Import(typeof(ISettings))]
private Settings _settings;
}
设置类:
public class Settings : ISettings
{
public string Name { get; set; }
public string Password { get; set; }
public Settings()
{
}
public Settings(string name, string pass)
{
Name = name;
Password = pass;
}
}
I am trying to export a field called Settings from my Main form to a Plugin as shown in the code below. I am using the Main Form function called CreateSettings() to update the private _settings field. But, when I do that, the imported Plugin Settings never changes and is always the original initialized values "defaultname" and "defaultpass". I am not sure what is going on?
Main Form:
public partial class Form1 : Form
{
[Export(typeof(ISettings))]
private Settings _settings = new Settings("defaultname", "defaultpass");
private void CreateSettings(name, password)
{
_settings = new Settings(name, password);
}
}
Plugin Control:
[Export(typeof(IPlugin))]
public partial class MyPlugin : UserControl, IPlugin
{
[Import(typeof(ISettings))]
private Settings _settings;
}
Settings Class:
public class Settings : ISettings
{
public string Name { get; set; }
public string Password { get; set; }
public Settings()
{
}
public Settings(string name, string pass)
{
Name = name;
Password = pass;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一旦解决了导入问题,将原始导出更改为新实例将不会更新导入类。如果您需要实际更改实例引用,一种选择是将其包装在引用不会更改的其他对象中,然后导入该引用。
或者,您可以使用概述的技术来执行动态重组这里。我认为简单地导入公开可变设置实例的上下文“服务”会更干净。
Once the import has been resolved, changing the original export to a new instance will not update the importing classes. If you need to actually change the instance reference, one option is to wrap it up in some other object whose reference won't change and Import that reference.
Alternately, you can perform dynamic recomposition, using a technique as outlined here. I think it's cleaner to simply import a context 'service' which exposes the mutable settings instance.