Created
December 29, 2014 21:53
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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