CodePaste Logo
New Snippet New Recent Snippets Recent Snippets My Snippets My Snippets My Favorites Favorites Web Code Search Snippets Search
Sign inor Register
Language: csharp

Repeatable MEF metadata

1750 Views   
class Program { static void Main(string[] args) { var instance = new Program(); var cat = new AssemblyCatalog(typeof(Program).Assembly); var container = new CompositionContainer(cat); container.ComposeParts(instance); foreach (var plug in instance.Plugins) { foreach (var category in plug.Metadata.Categories) { Console.ForegroundColor = ConsoleColor.Yellow; Console.Write("{0}, ", category); Console.ResetColor(); } Console.WriteLine(string.Empty); plug.Value.Write(); } Console.ReadLine(); } [ImportMany] public Lazy<IPlug, IMetadataView>[] Plugins { get; private set; } } public enum Category { Travel, Game, City, News } //[InheritedExport] // do not use inherited export (for some reason it don't working well with metadata) public interface IPlug { void Write(); } public interface IMetadataView { Category[] Categories { get; } } [MetadataAttribute] [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class CategoryAttribute : Attribute { public CategoryAttribute(Category category) { Categories = category; } public Category Categories { get; private set; } } [Export(typeof(IPlug))] [ExportMetadata("Categories", Category.Travel, IsMultiple = true)] // using untyped metadata considered as bad practice [ExportMetadata("Categories", Category.City, IsMultiple = true)] // using untyped metadata considered as bad practice public class NewYork : IPlug { public void Write() { Console.WriteLine("New York"); } } [Export(typeof(IPlug))] [Category(Category.Game)] [Category(Category.News)] public class Football : IPlug { public void Write() { Console.WriteLine("Football"); } }
by bnaya
  January 29, 2010 @ 4:10am
Tags:
Add a comment


Report Abuse
brought to you by:
West Wind Techologies