Search code examples
c#.netmef

MEF: DirectoryPartCatalog


I'm trying to write a simple MEF demo to learn about it. I'm following this tutorial, but it seems to be outdated. The downloadable example works, but it uses an included assembly that is 2 versions older (2008.9.4.0) than the current one (4.0) that ships with Framwework 4.

In particular, it uses DirectoryPartCatalog that I cannot find anywhere in the newest library. Could anyone provide an example on how to discover pluggable assemblies from a directory with the current version of MEF?

Thanks


Solution

  • You need to make several changes to make this sample compile and run with builtin version of System.ComponentModel.Composition.

    class Program
    {
        [ImportMany] // [Import]
        public IEnumerable<string> Messages { get; set; }
    
        [ImportMany] // [Import]
        public IEnumerable<IOutputString> OutputSet { get; set; }
    
        [Import("OutputMessages")]
        public Action<IEnumerable<IOutputString>, IEnumerable<string>> OutputMessages { get; set; }
    
        public void Run()
        {
    
            var catalog = new AggregateCatalog(); // AggregatingComposablePartCatalog
            catalog.Catalogs.Add(new DirectoryCatalog(@"..\..\..\ExternalMessages\bin\Debug")); // DirectoryPartCatalog
            catalog.Catalogs.Add(new DirectoryCatalog(@"..\..\..\ExtraMessages")); // DirectoryPartCatalog
            catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly())); // AttributedAssemblyPartCatalog
            var container = new CompositionContainer(catalog); // CompositionContainer(catalog.CreateResolver());
    
            // container.AddPart(this);
            // container.Compose();
            container.ComposeParts(this);
    
            OutputMessages(OutputSet, Messages);
    
        }
    
        static void Main(string[] args)
        {
            Program p = new Program();
            p.Run();
        }
    }