据我所知,如果声明了一个变量Lazy
,然后当我们使用Value
财产。
我需要传递一些参数给它Lazy
实例但找不到正确的语法。
这不是我的设计,我正在使用 MEF 并且ExportFactory
,它返回我Lazy
我的零件的实例。我的部件有构造函数,我需要使用一些参数调用这些构造函数。
您可以导出自己的Func
反而:
public class FooFactory
{
[Export(typeof(Func<string,int,ExportLifetimeContext<IFoo>>))]
public ExportLifetimeContext<IFoo> CreateFoo(string param1, int param2)
{
Foo foo = new Foo(param1, param2);
return new ExportLifetimeContext<IFoo>(foo,
delegate
{
// Clean-up action code goes here. The client might not be able
// to do this through the IFoo interface because it might not
// even expose a Dispose method.
//
// If you created other hidden dependencies in order to construct
// Foo, you could also clean them up here.
foo.Dispose();
});
}
}
并将其导入到其他地方:
[Export(typeof(ISomething))]
public class FooUser : ISomething
{
private readonly Func<string,int,ExportLifetimeContext<IFoo>> fooFactory;
[ImportingConstructor]
public FooUser(Func<string,int,ExportLifetimeContext<IFoo>> fooFactory)
{
this.fooFactory = fooFactory;
}
public void DoSomething()
{
using (var fooLifetime = this.fooFactory("hello", 3))
{
IFoo foo = fooLifetime.Value;
...
}
}
}
如果您不需要清理操作,那么您可以通过扔掉所有的来大大简化这一过程ExportLifetimeContext
stuff.
然而,一些实现IFoo
可能是一次性的(或依赖于其他一次性物品),而其他则不是。所以最正确的做法是在抽象中构建一个“我已经完成了这个对象”的信号,这就是ExportLifetimeContext
提供。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)