Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/// <summary>
/// Static helper class to debug failed MEF composition.
/// </summary>
public static class MefDebuggingHelper
{
/// <summary>
/// Writes missing import definitions to the debug console.
/// </summary>
/// <param name="container"></param>
[Conditional("DEBUG")]
public static void PrintMissingImports(CompositionContainer container)
{
var missingImports = GetMissingImports( container );
if( missingImports.Count == 0 )
{
return;
}
Debug.WriteLine( string.Empty );
Debug.WriteLine( "=============== Missing Imports ===============" );
foreach( var missing in missingImports )
{
Debug.WriteLine( missing );
}
Debug.WriteLine( "===============================================" );
Debug.WriteLine( string.Empty );
}
private static List<string> GetMissingImports(CompositionContainer container )
{
var brokenExports = GetBrokenExports(container);
return container.Catalog
.SelectMany( part => part.ImportDefinitions )
.Where( impDef => IsInvalidImport(container, impDef) )
.Select( impDef => impDef.ContractName )
.Distinct()
.Where( contract => !contract.Contains( "ExportFactory" ) )
.Where( contract => !brokenExports.Contains( contract ) )
.OrderBy( contract => contract )
.ToList();
}
private static List<string> GetBrokenExports(CompositionContainer container)
{
return container.Catalog
.Where( part => part.ImportDefinitions.Any( impDef => IsInvalidImport(container, impDef) ) )
.SelectMany( part => part.ExportDefinitions )
.Select( exDef => exDef.ContractName )
.Distinct()
.OrderBy( c => c )
.ToList();
}
private static bool IsInvalidImport(CompositionContainer container, ImportDefinition impDef )
{
try
{
container.GetExports( impDef );
}
catch
{
return true;
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.