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.