初始化惰性实例时,将参数传递给构造函数

Xaq*_*ron 4 c# constructor mef lazy-initialization

据我所知,如果声明了变量Lazy,那么当我们使用该Value属性时会调用它的构造函数.

我需要将一些参数传递给此Lazy实例,但无法找到正确的语法.这不是我的设计,我正在使用MEF ExportFactory,它会返回我Lazy的部件实例.我的部分有构造函数,我需要用一些参数调用这些构造函数.

Wim*_*nen 8

您可以导出自己的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();
            });
    }
}
Run Code Online (Sandbox Code Playgroud)

并将其导入其他地方:

[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;
            ...
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您不需要清理操作,那么您可以通过丢弃所有ExportLifetimeContext内容来大大简化这一过程.

然而,一些实施方式IFoo可能是一次性的(或依赖于其他一次性物体)而另一些则不是.因此,最正确的做法是将"我已完成此对象"信号构建到抽象中,这就是ExportLifetimeContext提供的.