views:

25

answers:

1

Hello,

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

+1  A: 

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.

Daniel Plaisted
+1 Ding ding. Make your IFooTracker static and IDisposable to clean up the registrations but this is the way you keep track of instances of anything.
Jimmy Hoffa