Gishu
Gishu

Reputation: 136613

Does the MEF Container.Dispose dispose added catalogs?

This is similar to how my code looks

var catalog = new AssemblyCatalog(typeof(Program).Assembly);
_container = new CompositionContainer(catalog);

Code Analysis is showing a warning CA2000: call Dispose on catalog before all references to it are out of scope.

So I'm not sure if I need to suppress the warning or turn _catalog into a field + Dispose it.

The MEF Docs don't seem to mention this.

Upvotes: 6

Views: 997

Answers (2)

Wes Haggard
Wes Haggard

Reputation: 4364

As Wim already discovered neither the CompsitionContainer nor the CatalogExportProvider will call dispose on the catalog. Neither of them created the catalog thus neither of them own it and as such will not call Dispose on it. Whoever constructs the catalog should be the one that disposes it.

There are a lot of scenarios where someone would want to share a catalog instance with multiple containers which is why the container doesn't have ownership of the catlaog and therefore doesn't dispose it.

Upvotes: 3

Wim Coenen
Wim Coenen

Reputation: 66723

According to the MEF Preview 9 source code (which probably closely matches the code that shipped in .NET 4) CompositionContainer will wrap the catalog in a CatalogExportProvider. This export provider is stored in a field and disposed along with the container. However, CatalogExportProvider.Dispose will not in turn dispose the wrapped ComposablePartCatalog.

Therefore the answer is no: CompositionContainer does not dispose the catalog.

You can verify this by running this code, which will not print anything to the console:

class MyCatalog : ComposablePartCatalog
{
   protected override void Dispose(bool disposing)
   {
      Console.WriteLine("Disposed!");
      base.Dispose();
   }

   public override IQueryable<ComposablePartDefinition> Parts
   {
      get { throw new NotImplementedException(); }
   }
}

class Program
{
   static void Main(string[] args)
   {
      var container = new CompositionContainer(new MyCatalog());
      container.Dispose();
      Console.ReadKey();
   }
}

Upvotes: 4

Related Questions