Dynamic Instantiation

A Lazy Import provides an importer with exactly one instance of the exported contract. The underlying value is created on first use with subsequent requests returning the same instance.

[Import]
Lazy<IFoo> foo;

// elsewhere in the same class

Assert.AreSame(foo.Value, foo.Value);
<Import()>
Private foo As Lazy(Of IFoo) 

' elsewhere in the same class

Assert.AreSame(foo.Value, foo.Value) 

ExportFactory<T>

Sometimes, a part needs to create multiple non-shared instances of an export on-the-fly. For example an order management application needs to create new OrderViewModels on the fly as a new order is created. For these situations, ExportFactory<T>, rather than Lazy<T>, is the appropriate type to import:

[Export]
public class OrderController {

  [Import] 
  public ExportFactory<OrderViewModel> OrderVMFactory {get;set;}

  public OrderViewModel CreateOrder() {
    return OrderVMFactory.CreateExport().Value;
  }
}
<Export()>
Public Class OrderController

    <Import()>
    Public Property OrderVMFactory() As ExportFactory(Of OrderViewModel) 

    Public Function CreateOrder() As OrderViewModel
        Return OrderVMFactory.CreateExport().Value
    End Function
End Class

The OrderController above imports a factory for creating OrderViewModels. Each type the application calls CreateOrder, the controller will use the factory to manufacture a new ViewModel instance. That ViewModel is created by the underlying container which will provide it's imports.

Importing a ExportCreator<T> is very similar to an import of Lazy<T>. The same rules for determining contract names and types apply, and the ExportCreator<T, TMetadata> type presents strongly-typed metadata in the same way as Lazy<T, TMetadata>.

ExportLifetimeContext<T>

The return value of ExportCreator<T>.CreateExport() is a ExportLifetimeContext<T>. This type exposes the created part's exported value through the Value property. The type also provides an implementation of IDisposable, so that when the exported value is no longer required, the underlying part and all of its dependencies can be cleaned up.

More details can be found in this blog post.

Last edited Aug 9, 2010 at 5:55 PM by haveriss, version 10

Comments

EvilShrike Aug 18, 2010 at 12:51 PM 
Why ExportFactory<T> is only in Silverlight but in Desktop .NET ??

laedit May 8, 2010 at 1:20 PM 
It's ExportFactory<T> instead of ExportCreator<T>, no ?

gblock Mar 27, 2010 at 5:38 PM 
HI Denis. We don't have an official PartCreator for non-SL in the box (we never did). We are looking to ship it within MEF in the future. I'll look into getting our sample for the desktop updated.

DenisVuyka Feb 8, 2010 at 10:00 AM 
Guys, as now PartCreator seems to be completely deprecated for non-SL what is the alternative to those existing in SL for the moment? I don't think it is good deprecating something without providing a good equivalent. Are we back to custom factories age again? Thanks.