为 MEF 初始化提供委托
是否可以向 MEF 容器提供惰性对象初始值设定项?
这是一个例子:
[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 initialization here
return foo;
});
container.ComposeExportedValue(initializer);
CompositionBatch batch = new CompositionBatch();
container.Compose(batch);
var export = container.GetExportedValue<Bar>(); // composition fails
这段代码不起作用,但如果我调用container.ComposeExportedValue(new Foo()),它就会起作用。 我想直接传递一个委托来创建惰性对象。是否可以在不需要定制出口提供商的情况下实现?
谢谢
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 initialization 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Lazy
对于 MEF 导入具有特殊含义。 MEF 不会逐字查找Lazy
导出,而是查找T
导出并延迟实例化该部分。尝试使用此类型来代替导入和导出:
由于它是不同的类型,因此它对于 MEF 应该没有特殊含义。
Lazy<T>
has a special meaning for MEF imports. Rather than looking literally for aLazy<T>
export, MEF will look for aT
export and instantiate that part lazily.Try to use this type instead for your imports and exports:
Since it is a different type, it should hold no special meaning for MEF.