This project has moved and is read-only. For the latest updates, please go here.

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.

Lazy<IFoo> foo;

// elsewhere in the same class

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

' elsewhere in the same class

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


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:

public class OrderController {

  public ExportFactory<OrderViewModel> OrderVMFactory {get;set;}

  public OrderViewModel CreateOrder() {
    return OrderVMFactory.CreateExport().Value;
Public Class OrderController

    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>.


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 6:55 PM by haveriss, version 10


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

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

gblock Mar 27, 2010 at 6: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 11: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.