Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 returns me Lazy instances of my parts. My parts have constructors and I need to call these constructors with some parameters.

like image 696
Xaqron Avatar asked Dec 22 '22 20:12

Xaqron


2 Answers

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.

like image 189
Wim Coenen Avatar answered Feb 11 '23 07:02

Wim Coenen


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.

like image 40
Daniel Plaisted Avatar answered Feb 11 '23 08:02

Daniel Plaisted