MEF and two instances of the same class

How to place two instances of the same class or interface in MEF? How do I get them?

+3
source share
1 answer

By default, any part registered in the MEF uses a single-element life cycle management strategy (one per container). This is indicated by default CreationPolicy Shared. I think you need to clearly understand what you need ...

Do you need every instance of a new instance?

If so, you can add PartCreationPolicyAttributeto your export:

[PartCreationPolicy(CreationPolicy.NonShared), Export(typeof(IFoo))]
public class Foo : IFoo { }

Each time you create a class using your container, you will get a new instance Foo.

Do you need two independent instances at the same time?

, . ExportFactory, , , :

[Import]
public ExportFactory<IFoo> Factory { get; set; }

public IFoo CreateFoo()
{
    return Factory.CreateExport().Value;
}

( ExportFactory<T> , Silverlight, - ExportFactory<T> .NET 4, Silverlight).

+8

All Articles