/src/LinFu.AOP/FieldInterception/ImplementFieldInterceptionHostWeaver.cs

http://github.com/philiplaureano/LinFu · C# · 81 lines · 44 code · 12 blank · 25 comment · 8 complexity · 99de68d4b0f861cc760bce32ec2117ed MD5 · raw file

  1. using System;
  2. using LinFu.AOP.Cecil.Interfaces;
  3. using LinFu.AOP.Interfaces;
  4. using LinFu.Reflection.Emit;
  5. using Mono.Cecil;
  6. namespace LinFu.AOP.Cecil
  7. {
  8. /// <summary>
  9. /// Represents a type weaver that modifies types to implement the <see cref="IFieldInterceptionHost" /> interface.
  10. /// </summary>
  11. public class ImplementFieldInterceptionHostWeaver : ITypeWeaver
  12. {
  13. private readonly Func<TypeReference, bool> _filter;
  14. private TypeReference _hostInterfaceType;
  15. private TypeReference _interceptorPropertyType;
  16. /// <summary>
  17. /// Initializes a new instance of the ImplementFieldInterceptionHostWeaver class.
  18. /// </summary>
  19. /// <param name="filter">The filter that determines which types should be modified.</param>
  20. public ImplementFieldInterceptionHostWeaver(Func<TypeReference, bool> filter)
  21. {
  22. _filter = filter;
  23. }
  24. /// <summary>
  25. /// Determines whether or not a type should be modified.
  26. /// </summary>
  27. /// <param name="item"></param>
  28. /// <returns><c>true</c> if the type should be modified; otherwise, it will return <c>false</c>.</returns>
  29. public bool ShouldWeave(TypeDefinition item)
  30. {
  31. if (item.Name == "<Module>")
  32. return false;
  33. if (!item.IsClass || item.IsInterface)
  34. return false;
  35. if (_filter != null)
  36. return _filter(item);
  37. return true;
  38. }
  39. /// <summary>
  40. /// Modifies the target type.
  41. /// </summary>
  42. /// <param name="type">The type to be modified.</param>
  43. public void Weave(TypeDefinition type)
  44. {
  45. // Implement IActivatorHost only once
  46. if (type.Interfaces.Contains(_hostInterfaceType))
  47. return;
  48. type.AddProperty("FieldInterceptor", _interceptorPropertyType);
  49. if (!type.Interfaces.Contains(_hostInterfaceType))
  50. type.Interfaces.Add(_hostInterfaceType);
  51. }
  52. /// <summary>
  53. /// Adds additional members to the target module.
  54. /// </summary>
  55. /// <param name="host">The host module.</param>
  56. public void AddAdditionalMembers(ModuleDefinition host)
  57. {
  58. }
  59. /// <summary>
  60. /// Imports references into the target module.
  61. /// </summary>
  62. /// <param name="module">The module containing the type to be modified.</param>
  63. public void ImportReferences(ModuleDefinition module)
  64. {
  65. _hostInterfaceType = module.ImportType<IFieldInterceptionHost>();
  66. _interceptorPropertyType = module.ImportType<IFieldInterceptor>();
  67. }
  68. }
  69. }