How do I get MEF to recompose when I change a part?

前端 未结 1 1117
醉酒成梦
醉酒成梦 2020-12-29 17:54

I am trying to get MEF to recompose all the parts that it knows about when I update an instance that is exported. Essentially I want to have MEF update all my parts that imp

相关标签:
1条回答
  • 2020-12-29 18:15

    You have a few things a little off for the scenario you are trying to accomplish.

    First: If you want to add/remove/change a particular export it must not be in the catalog itself so you should remove your Config class which has the Export settings property. That is being created by the CatalogExportProvider and is the reason you are seeing a null value in your collection.

    Try the following:

    public class Program
    {
        [ImportMany(AllowRecomposition=true)]
        public IEnumerable<Settings> Settings { get; set; }
    
        public void RunTest()
        {
            AggregateCatalog catalog = new AggregateCatalog();
            catalog.Catalogs.Add(new AssemblyCatalog(typeof(Settings).Assembly));
    
            CompositionContainer container = new CompositionContainer(catalog);
    
            // Settings should have 0 values.
            container.ComposeParts(this);
            Contract.Assert(this.Settings.Count() == 0);
    
            CompositionBatch batch = new CompositionBatch();
    
            // Store the settingsPart for later removal...
            ComposablePart settingsPart = 
                batch.AddExportedValue(new Settings { ConnectionString = "Value1" });
    
            container.Compose(batch);
    
            // Settings should have "Value1"
            UsesSettings result = container.GetExportedValue<UsesSettings>();
            Contract.Assert(result.TheSettings.ConnectionString == "Value1");
    
            // Settings should have 1 value which is "Value1";
            Contract.Assert(this.Settings.Count() == 1);
            Contract.Assert(this.Settings.First().ConnectionString == "Value1");
    
            // Remove the old settings and replace it with a new one.
            batch = new CompositionBatch();
            batch.RemovePart(settingsPart);
            batch.AddExportedValue(new Settings { ConnectionString = "Value2" });
            container.Compose(batch);
    
            // result.Settings should have "Value2" now.
            Contract.Assert(result.TheSettings.ConnectionString == "Value2");
    
            // Settings should have 1 value which is "Value2"
            Contract.Assert(this.Settings.Count() == 1);
            Contract.Assert(this.Settings.First().ConnectionString == "Value2");
        }
    }
    public class Settings
    {
        public string ConnectionString = "default value";
    }
    
    [Export(typeof(UsesSettings))]
    public class UsesSettings
    {
        [Import(typeof(Settings), AllowRecomposition = true)]
        public Settings TheSettings { get; set; }
    }
    
    0 讨论(0)
提交回复
热议问题