/src/LinFu.IoC/Configuration/Injectors/AttributedFieldInjectionFilter.cs

http://github.com/philiplaureano/LinFu · C# · 61 lines · 32 code · 5 blank · 24 comment · 2 complexity · dd31cea3ade8f92b466e2df59023d6e9 MD5 · raw file

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using LinFu.IoC.Configuration.Interfaces;
  6. using LinFu.IoC.Interfaces;
  7. namespace LinFu.IoC.Configuration
  8. {
  9. /// <summary>
  10. /// A default implementation of the <see cref="IMemberInjectionFilter{TMember}" />
  11. /// class that returns fields which have the <see cref="InjectAttribute" />
  12. /// defined.
  13. /// </summary>
  14. public class AttributedFieldInjectionFilter : BaseMemberInjectionFilter<FieldInfo>
  15. {
  16. private readonly Type _attributeType;
  17. /// <summary>
  18. /// Initializes the class and uses the <see cref="InjectAttribute" />
  19. /// to specify which field should be automatically injected with
  20. /// services from the container.
  21. /// </summary>
  22. public AttributedFieldInjectionFilter()
  23. {
  24. _attributeType = typeof(InjectAttribute);
  25. }
  26. /// <summary>
  27. /// Initializes the class and uses the <paramref name="attributeType" />
  28. /// to specify which fields should be automatically injected with
  29. /// services from the container.
  30. /// </summary>
  31. /// <param name="attributeType">The custom property attribute that will be used to mark properties for automatic injection.</param>
  32. public AttributedFieldInjectionFilter(Type attributeType)
  33. {
  34. _attributeType = attributeType;
  35. }
  36. /// <summary>
  37. /// Determines which members should be selected from the <paramref name="targetType" />
  38. /// using the <paramref name="container" />
  39. /// </summary>
  40. /// <param name="targetType">The target type that will supply the list of members that will be filtered.</param>
  41. /// <param name="container">The target container.</param>
  42. /// <returns>A list of <see cref="FieldInfo" /> objects that pass the filter description.</returns>
  43. protected override IEnumerable<FieldInfo> GetMembers(Type targetType, IServiceContainer container)
  44. {
  45. // The field type must exist in the container and must be marked as public
  46. var results =
  47. from field in targetType.GetFields(BindingFlags.Public | BindingFlags.Instance)
  48. let fieldType = field.FieldType
  49. let attributes = field.GetCustomAttributes(_attributeType, false)
  50. where attributes != null && attributes.Length > 0 &&
  51. container.Contains(fieldType)
  52. select field;
  53. return results;
  54. }
  55. }
  56. }