我知道是否声明了变量 Lazy, ,然后我们使用的构造函数 Value 财产。

我需要传递一些参数 Lazy 实例但找不到正确的语法。这不是我的设计,我正在使用MEF和 ExportFactory, ,它返回我 Lazy 我的各个实例。我的零件有构造函数,我需要用一些参数调用这些构造函数。

有帮助吗?

解决方案

MEF没有内置的方式供您将构造函数参数传递给零件时,当您使用ExportFactory创建它时。像Wim Coenen所建议的那样,可能是实现自己想要的最佳方法。

其他提示

你可以自己出口 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 提供。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top