Guest User

Untitled

a guest
May 27th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.95 KB | None | 0 0
  1. public class FactoryExportProvider<T> : ExportProvider
  2. {
  3. private readonly IList<FactoryExportDefinition<T>> exports = new List<FactoryExportDefinition<T>>();
  4.  
  5. public FactoryExportProvider(Func<Type, T> resolutionMethod)
  6. : this(Assembly.GetExecutingAssembly(), resolutionMethod)
  7. {
  8. }
  9.  
  10. public FactoryExportProvider(Assembly assembly, Func<Type, T> resolutionMethod)
  11. {
  12. IEnumerable<Type> interfaces = from t in assembly.GetTypes()
  13. where t.IsInterface
  14. select t;
  15.  
  16. ComposeTypes(interfaces, resolutionMethod);
  17. }
  18.  
  19. public FactoryExportProvider(IEnumerable<Type> types, Func<Type, T> resolutionMethod)
  20. {
  21. ComposeTypes(types, resolutionMethod);
  22. }
  23.  
  24. protected override IEnumerable<Export> GetExportsCore(ImportDefinition importDefinition)
  25. {
  26. IList<Export> returnExports = new List<Export>();
  27. var constraint = importDefinition.Constraint.Compile();
  28. var foundExports = from d in exports
  29. where constraint(d)
  30. select new Export(d, () => d.ResolutionMethod(d.ServiceType));
  31.  
  32. if (importDefinition.Cardinality == ImportCardinality.ZeroOrMore)
  33. returnExports = foundExports.ToList();
  34. else if (foundExports.Count() == 1)
  35. returnExports.Add(foundExports.First());
  36.  
  37. return returnExports;
  38. }
  39.  
  40. private void ComposeTypes(IEnumerable<Type> serviceTypes, Func<Type, T> resolutionMethod)
  41. {
  42. foreach (Type type in serviceTypes)
  43. {
  44. Type interfaceType = (from i in type.GetInterfaces()
  45. where i == typeof (T)
  46. select i).SingleOrDefault();
  47.  
  48. if (interfaceType != null)
  49. exports.Add(new FactoryExportDefinition<T>(type.ToString(), type, resolutionMethod));
  50. }
  51. }
  52. }
Add Comment
Please, Sign In to add comment