2
0

MefUtils.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. using System.Collections.Generic;
  2. using System.ComponentModel.Composition.Hosting;
  3. using System.ComponentModel.Composition.Primitives;
  4. using System.Linq;
  5. using System.Reflection;
  6. namespace MediaBrowser.Common.Mef
  7. {
  8. public static class MefUtils
  9. {
  10. /// <summary>
  11. /// Plugins that live on both the server and UI are going to have references to assemblies from both sides.
  12. /// But looks for Parts on one side, it will throw an exception when it seems Types from the other side that it doesn't have a reference to.
  13. /// For example, a plugin provides a Resolver. When MEF runs in the UI, it will throw an exception when it sees the resolver because there won't be a reference to the base class.
  14. /// This method will catch those exceptions while retining the list of Types that MEF is able to resolve.
  15. /// </summary>
  16. public static CompositionContainer GetSafeCompositionContainer(IEnumerable<ComposablePartCatalog> catalogs)
  17. {
  18. var newList = new List<ComposablePartCatalog>();
  19. // Go through each Catalog
  20. foreach (var catalog in catalogs)
  21. {
  22. try
  23. {
  24. // Try to have MEF find Parts
  25. catalog.Parts.ToArray();
  26. // If it succeeds we can use the entire catalog
  27. newList.Add(catalog);
  28. }
  29. catch (ReflectionTypeLoadException ex)
  30. {
  31. // If it fails we can still get a list of the Types it was able to resolve and create TypeCatalogs
  32. var typeCatalogs = ex.Types.Where(t => t != null).Select(t => new TypeCatalog(t));
  33. newList.AddRange(typeCatalogs);
  34. }
  35. }
  36. return new CompositionContainer(new AggregateCatalog(newList));
  37. }
  38. }
  39. }