Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the MEF Container.Dispose dispose added catalogs?

Tags:

mef

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.

like image 417
Gishu Avatar asked Apr 15 '11 11:04

Gishu


1 Answers

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();
   }
}
like image 162
Wim Coenen Avatar answered Nov 14 '22 22:11

Wim Coenen