Skip to content

Instantly share code, notes, and snippets.

@cpoDesign
Created December 29, 2014 21:53
Show Gist options
  • Select an option

  • Save cpoDesign/df70d4db0e00a4f935d7 to your computer and use it in GitHub Desktop.

Select an option

Save cpoDesign/df70d4db0e00a4f935d7 to your computer and use it in GitHub Desktop.
MEF CompositionClass - allows user to implement MEF into application using couple lines of code.
using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.IO;
namespace CpoDesign.Service.Core
{
/// <summary>
/// MEF Compositon class
/// </summary>
/// <code>
/// var path = AppDomain.CurrentDomain.BaseDirectory;
/// var composition = new Composition();
/// composition.ComposeContainer(path);
/// composition.AddPart(this);
/// composition.Compose();
/// </code>
public class Composition
{
private CompositionBatch _batch;
private CompositionContainer _container;
public void ComposeContainer(string path, bool hasPlugins = false)
{
AggregateCatalog catalog;
if (hasPlugins)
{
catalog = new AggregateCatalog(
new DirectoryCatalog(Path.Combine(path, "Plugins")),
new DirectoryCatalog(path));
}
else
{
catalog = new AggregateCatalog(new DirectoryCatalog(path));
}
_container = new CompositionContainer(catalog);
}
public void AddPart<T>(T type)
{
if (_batch == null) _batch = new CompositionBatch();
_batch.AddPart(type);
}
public void Compose()
{
try
{
_container.Compose(_batch);
}
catch (CompositionException ex)
{
foreach (var error in ex.Errors)
{
Console.WriteLine(error.Description);
}
throw;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment