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

http://github.com/philiplaureano/LinFu · C# · 58 lines · 33 code · 5 blank · 20 comment · 3 complexity · 93dac1a1a0b71b3432b2fb7c36abc2bd 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 methods which have the <see cref="InjectAttribute" />
  12. /// defined.
  13. /// </summary>
  14. public class AttributedMethodInjectionFilter : BaseMemberInjectionFilter<MethodInfo>
  15. {
  16. private readonly Type _attributeType;
  17. /// <summary>
  18. /// Initializes the class with the <see cref="InjectAttribute" /> as the
  19. /// default injection attribute.
  20. /// </summary>
  21. public AttributedMethodInjectionFilter()
  22. {
  23. _attributeType = typeof(InjectAttribute);
  24. }
  25. /// <summary>
  26. /// Initializes the class and uses the <paramref name="attributeType" />
  27. /// as the custom injection attribute.
  28. /// </summary>
  29. /// <param name="attributeType"></param>
  30. public AttributedMethodInjectionFilter(Type attributeType)
  31. {
  32. _attributeType = attributeType;
  33. }
  34. /// <summary>
  35. /// Returns the methods that have the custom attribute type defined.
  36. /// </summary>
  37. /// <param name="targetType">The target type that contains the target methods.</param>
  38. /// <param name="container">The host container.</param>
  39. /// <returns>The list of methods that have the custom attribute type defined.</returns>
  40. protected override IEnumerable<MethodInfo> GetMembers(Type targetType,
  41. IServiceContainer container)
  42. {
  43. var results =
  44. from method in targetType.GetMethods(BindingFlags.Public | BindingFlags.Instance)
  45. let attributes = _attributeType != null
  46. ? method.GetCustomAttributes(_attributeType, false)
  47. : null
  48. where attributes != null && attributes.Length > 0
  49. select method;
  50. return results;
  51. }
  52. }
  53. }