Search code examples
.netmefstatic-methods

Can you hydrate a static property using MEF?


can I hydrate this inside the class's static constructor?

public class Connect:IDTExtensibility2, IDTCommandTarget
  static Connect()
    {
        //hydrate static properties?
    }
    [Import]
    public static Action<ProjectLogicChecks> Display { get; set; }

[Export(typeof(Action<ProjectLogicChecks>))]
    private static void DisplayResults( CheckProcesses _checkResults)
{
    MessageBox.Show(_checkResults.ProjectLogicCheck.AssemblyName + " has problems=" +
                    _checkResults.ProjectLogicCheck.HasProblems);
}

Solution

  • It was easier than I thought it would be.

     static Connect()
        {
            var batch = new CompositionBatch( );
            CompositionContainer container;
            var reflectionCatalog = new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly( ));
    
            var extensionPath = System.IO.Path.Combine(Environment.CurrentDirectory, "extensions");
            if (System.IO.Directory.Exists(extensionPath))
            {
                var directoryCatalog = new DirectoryCatalog(extensionPath);
                var defaultCatalogEp = new CatalogExportProvider(reflectionCatalog);
                container=new CompositionContainer(directoryCatalog, defaultCatalogEp);
                defaultCatalogEp.SourceProvider=container;
            }
            else
                container = new CompositionContainer(reflectionCatalog);
    
            container.Compose(batch);
     //Setting a static property
            Display=container.GetExportedValue<Action<IEnumerable< ProjectLogicChecks>>>( );
        }
    

    Changed the type to Action<IEnumerable<ProjectLogicChecks>> so that I could display results for multiple projects or a whole solution instead of just the one.

    I followed this article to get the static property set, then this to provide local defaults in case there is no extension present.