This project has moved. For the latest updates, please go here.

Getting shared instances

May 5, 2009 at 3:41 AM

I am attempting to use the shared part creation policy for a MEF export. It does not, however, seem to work the way I was thinking. I do the composition twice in my application and each time get a fresh copy of the object. I've proved this by adding an instance counter to the object instanciation

    static int instCount = 0;

public FakeAutocompleteRepository()

and running it all in debug. Indeed the second time I do a composition I get a new copy of the FakeAutocompleteRepository with instCount = 2. The export section contains

[ExportMetadata("IsTesting", "True")]
class FakeAutocompleteRepository : IAutocompleteRepository
{ ... }

Is there some trick to getting the same instance for subsiquent requests? In case it is something I'm doing during the composition this is how I'm doing that

var catalog = new AggregateCatalog();
.Catalogs.Add(new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly()));
.Catalogs.Add(new DirectoryCatalog("."));
var container = new CompositionContainer(catalog);
var batch = new CompositionBatch();

if (null != ConfigurationSettings.AppSettings["IsTesting"] && bool.Parse(ConfigurationSettings.AppSettings["IsTesting"]))
= container.GetExports<IAutocompleteRepository>().Where(expDef => expDef.Metadata.Keys.Contains("IsTesting")).Single().GetExportedObject();

Basically I'm trying to force a specific composition during testing. If you have a better idea for unit testing these compositions then I'm all ears.

May 5, 2009 at 9:59 PM
I actually cross posted this to stackoverflow as well ( and got an answer there.  I am using multiple containers so I get an instance for each.  I was wondering if there is so way to get the active containers or if it should be handled by something I write (singleton perhaps).  
May 5, 2009 at 10:01 PM
Edited May 5, 2009 at 10:01 PM

--oops, double post--

I actually cross posted this to stackoverflow and got an answer there (  It seems I need to have just one container.  Is there an approved of way to do this or should I handle it myself through singleton or something similar?