0

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;
    }
}
John_Sheares
  • 1,404
  • 2
  • 21
  • 34

1 Answers1

3

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.

Community
  • 1
  • 1
Dan Bryant
  • 27,329
  • 4
  • 56
  • 102
  • I changed the CreateSettings function, so that it does not create a new Settings object. It just updates the Name and Password properties for _settings. Not, sure if this is the best way of going about it. – John_Sheares Nov 02 '10 at 02:19
  • @John_Sheares, I've run into this problem when I have a Settings class that I'm persisting with Serialization. Deserialization requires creating a new instance, so if I want to re-load the configuration, none of my classes can be holding a cached reference to the stale configuration. It's always a bit awkward and I haven't found a good solution that I'm happy with. – Dan Bryant Nov 02 '10 at 03:31