Como faço para que o MEF recomponha quando troco uma peça?
Estou tentando fazer com que o MEF recomponha todas as partes que ele conhece quando atualizo uma instância que é exportada. Essencialmente, quero que o MEF atualize todas as minhas peças que importam um valor de configuração da cadeia de conexão quando ele é alterado. Tudo parece bom até o ponto em que quero mudar a instância. Se eu tentar ComposeParts com o valor atualizado, parece adicionar uma segunda instância de parte no contêiner e minhas importações são atualizadas, mas nulas.
Alguém pode apontar onde estou errado? Ou devo tentar usar o MEF dessa maneira?
Estou usando a visualização 9 do MEF e direcionando o .net framework 3.5 e o WPF.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
using System.Text;
using Shouldly;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
MainClass main = new MainClass();
main.RunTest();
}
}
public class MainClass
{
[ImportMany]
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);
container.SatisfyImportsOnce(this);
Config cfg = new Config
{
Settings = new Settings { ConnectionString = "Value1" },
};
// result is returned with a null settings value
UsesSettings result = container.GetExportedValue<UsesSettings>();
// this recomposes everything with the new value, result changes to have settings of Value1
container.ComposeParts(cfg);
// this line results in my import many enumerable returning 2 parts the Value1 setting and null
container.SatisfyImportsOnce(this);
result.TheSettings.ConnectionString.ShouldBe("Value1");
cfg.Settings = new Settings { ConnectionString = "Value2" };
// how do I tell the container to recompose now I have changed the config object,
// or how do I replace the part value with the new value?
// this line causes the result.Settings to return null
container.ComposeParts(cfg);
// this updates the ImportMany to 3 values, Value1, Value2 and null
container.SatisfyImportsOnce(this);
}
}
public class Settings
{
public string ConnectionString = "default value";
}
public class Config
{
[Export(typeof(Settings))]
public Settings Settings { get; set; }
}
[Export(typeof(UsesSettings))]
public class UsesSettings
{
[Import(typeof(Settings), AllowRecomposition = true)]
public Settings TheSettings { get; set; }
}
}