据我所知,如果声明了一个变量,那么当我们使用该属性Lazy
时就会调用它的构造函数。Value
我需要将一些参数传递给这个Lazy
实例,但找不到正确的语法。这不是我的设计,我使用的是 MEF ExportFactory
,它返回Lazy
了我的零件实例。我的零件有构造函数,我需要用一些参数调用这些构造函数。
据我所知,如果声明了一个变量,那么当我们使用该属性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
东西来大大简化它。
但是,某些实现IFoo
可能是一次性的(或依赖于其他一次性对象),而其他实现则不是。所以最正确的做法是在抽象中构建一个“我已经完成了这个对象”的信号,这就是ExportLifetimeContext
提供的。
当您使用 ExportFactory 创建零件时,MEF 没有内置方法可让您将构造函数参数传递给零件。像 Wim Coenen 建议的东西可能是实现您想要的最佳方式。