Hi Alex, thanks for your question! If I understood correctly your requirements are
1. Only read config once in the convient time before it is accessed.
2. Have thecondigprovider control the lifetime of the config.
I've created a small example that illustrates some MEF concepts, like ICompositionService that can be imported by a component (Provider) and be used to contribute to the pool of objects (release new configs). Another concept is subscribing for INotifyImport interface that can be used to execute code right after component is bound - that's the rime for Config component to initialize (be read).
Please let me know if that any close to what you were asking about...
[ContractType]
public interface IConfig { string Id { get; set; } }
[Export(typeof(IConfig))]
public class Config: INotifyImport
{
public string Id { get; set; }
public void ImportCompleted()
{
Console.WriteLine("Config is being read...");
}
}
public class ConfigProvider
{
ComponentBinder binder;
public void Provide()
{
if (binder != null)
{
CompositionService.RemoveValuesAndBinder(binder);
}
binder = new ReflectionBinder(new Config() { Id = Guid.NewGuid().ToString("N") });
CompositionService.AddBinder(binder);
CompositionService.Bind();
}
[Import]
public ICompositionService CompositionService { get; set; }
}
public class ConfigConsumer
{
[Import(IsOptional = true)]
public IConfig Config { get; set; }
}
class Program
{
static void Main(string[] args)
{
var container = new CompositionContainer();
var consumer = new ConfigConsumer();
var provider = new ConfigProvider();
container.AddComponent<ConfigProvider>(provider);
container.AddComponent<ConfigConsumer>(consumer);
container.Bind();
provider.Provide();
Console.WriteLine(consumer.Config.Id);
Console.WriteLine(consumer.Config.Id);
provider.Provide();
Console.WriteLine(consumer.Config.Id);
Console.ReadLine();
}
}
Alex Bulankou, Microsoft Corporation. This posting is provided "AS IS".