is it possible to provide a Lazy object initializer to a MEF container?
Here it is an example:
[Export]
public class Bar
{
[ImportingConstructor[
public Bar([Import] Lazy<Foo> foo)
{
// [..]
}
}
TypeCatalog catalog = new TypeCatalog(typeof(Bar));
CompositionContainer container = new CompositionContainer(catalog);
Lazy<Foo> initializer = new Lazy(() =>
{
Foo foo = new Foo();
// foo initiali开发者_StackOverflow社区zation here
return foo;
});
container.ComposeExportedValue(initializer);
CompositionBatch batch = new CompositionBatch();
container.Compose(batch);
var export = container.GetExportedValue<Bar>(); // composition fails
This piece of code doesn't work, while it works if I call container.ComposeExportedValue(new Foo()). I would like to directly pass a delegate to create the lazy object. Is it possible without the need for a custom export provider?
Thank you
Lazy<T>
has a special meaning for MEF imports. Rather than looking literally for a Lazy<T>
export, MEF will look for a T
export and instantiate that part lazily.
Try to use this type instead for your imports and exports:
public class LazyPart<T> : Lazy<T>
{
public LazyPart(Func<T> initializer) : base(initializer)
{
}
}
Since it is a different type, it should hold no special meaning for MEF.
精彩评论