MEF:导入的字段值未更新

发布于 2024-09-29 20:10:12 字数 962 浏览 2 评论 0原文

我正在尝试将一个名为“设置”的字段从主窗体导出到插件,如下面的代码所示。我正在使用名为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

此岸叶落 2024-10-06 20:10:12

一旦解决了导入问题,将原始导出更改为新实例将不会更新导入类。如果您需要实际更改实例引用,一种选择是将其包装在引用不会更改的其他对象中,然后导入该引用。

或者,您可以使用概述的技术来执行动态重组这里。我认为简单地导入公开可变设置实例的上下文“服务”会更干净。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文