Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class FactoryExportProvider<T> : ExportProvider
- {
- private readonly IList<FactoryExportDefinition<T>> exports = new List<FactoryExportDefinition<T>>();
- public FactoryExportProvider(Func<Type, T> resolutionMethod)
- : this(Assembly.GetExecutingAssembly(), resolutionMethod)
- {
- }
- public FactoryExportProvider(Assembly assembly, Func<Type, T> resolutionMethod)
- {
- IEnumerable<Type> interfaces = from t in assembly.GetTypes()
- where t.IsInterface
- select t;
- ComposeTypes(interfaces, resolutionMethod);
- }
- public FactoryExportProvider(IEnumerable<Type> types, Func<Type, T> resolutionMethod)
- {
- ComposeTypes(types, resolutionMethod);
- }
- protected override IEnumerable<Export> GetExportsCore(ImportDefinition importDefinition)
- {
- IList<Export> returnExports = new List<Export>();
- var constraint = importDefinition.Constraint.Compile();
- var foundExports = from d in exports
- where constraint(d)
- select new Export(d, () => d.ResolutionMethod(d.ServiceType));
- if (importDefinition.Cardinality == ImportCardinality.ZeroOrMore)
- returnExports = foundExports.ToList();
- else if (foundExports.Count() == 1)
- returnExports.Add(foundExports.First());
- return returnExports;
- }
- private void ComposeTypes(IEnumerable<Type> serviceTypes, Func<Type, T> resolutionMethod)
- {
- foreach (Type type in serviceTypes)
- {
- Type interfaceType = (from i in type.GetInterfaces()
- where i == typeof (T)
- select i).SingleOrDefault();
- if (interfaceType != null)
- exports.Add(new FactoryExportDefinition<T>(type.ToString(), type, resolutionMethod));
- }
- }
- }
Add Comment
Please, Sign In to add comment