开发者

Pass parameters to constructor, when initializing a lazy instance

As I know if a variable is declared Lazy, then its constructor is called when we use the Value property.

I need to pass some parameters to this Lazy instance but cannot find the correct syntax. This is not my design, I'm using MEF and ExportFactory, it ret开发者_StackOverflowurns me Lazy instances of my parts. My parts have constructors and I need to call these constructors with some parameters.


You could export your own Func instead:

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();
            });
    }
}

and import it elsewhere:

[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;
            ...
        }
    }
}

If you don't need the clean-up action then you could simplify this considerably by throwing out all the ExportLifetimeContext stuff.

However, some implementations of IFoo might be disposable (or depend on other disposable objects) while others are not. So the most correct thing to do is to build a "I'm done with this object" signal into the abstraction, which is what ExportLifetimeContext provides.


MEF doesn't have a built-in way for you to pass constructor parameters to a part when you create it with an ExportFactory. Something like what Wim Coenen suggests is probably the best way to achieve what you want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜