Florian Doyon
Florian Doyon

Reputation: 4186

Tracking instances created by a MEF container

I'm using MEF to create several instances of the same export.

I'd like to keep track of the instances I have created, and am either querying the container or using a recomposited collection, but I never get my instances...

Here's the code:

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

  class FooTracker{
     CompositionContainer _container; 
     int HowManyValues()
     {
       // this always returns 1 and invokes a constructor
       return _container.GetExportedValue<IFoo>().Count();
     }

     int HowManyExports(){
       // idem
       return _container.GetExports<IFoo>().Count();
     }

     // idem
     [ImportMany(AllowRecomposition=true,AllowRecomposition=true)]
     protected IEnumerable<IFoo> Foos { get; set; }
  }

What I would like is to get is the already existing instances, not create a new one if there aren't any.

Thanks, Florian

Upvotes: 1

Views: 299

Answers (1)

Daniel Plaisted
Daniel Plaisted

Reputation: 16744

MEF doesn't provide this functionality. You could do it by having each implementation of IFoo import an IFooTracker and call a method in IFooTracker to register the IFoo.

Upvotes: 1

Related Questions