/src/LinFu.AOP/Factories/TypeWeaverActionFactory.cs

http://github.com/philiplaureano/LinFu · C# · 54 lines · 32 code · 7 blank · 15 comment · 1 complexity · 0e587cf0c0fd423aa20a8ba522e8239e MD5 · raw file

  1. using System;
  2. using LinFu.AOP.Cecil.Interfaces;
  3. using LinFu.IoC.Configuration;
  4. using LinFu.IoC.Interfaces;
  5. using Mono.Cecil;
  6. namespace LinFu.AOP.Cecil.Factories
  7. {
  8. /// <summary>
  9. /// Represents a class that generates <see cref="Action{T1,T2}" /> instances
  10. /// that apply a specific method weaver (with the name given in the first delegate parameter)
  11. /// to a specific <see cref="TypeDefinition" /> instance.
  12. /// </summary>
  13. [Factory(typeof(Action<string, TypeDefinition>), ServiceName = "TypeWeaver")]
  14. public class TypeWeaverActionFactory : IFactory
  15. {
  16. /// <summary>
  17. /// Generates the <see cref="Action{T1, T2}" /> instance that will
  18. /// weave the target type.
  19. /// </summary>
  20. /// <param name="request">The <see cref="IFactoryRequest" /> that describes the service request.</param>
  21. /// <returns>The <see cref="Action{T1, T2}" /> instance that will weave the target type.</returns>
  22. public object CreateInstance(IFactoryRequest request)
  23. {
  24. var container = request.Container;
  25. Action<string, TypeDefinition> result =
  26. (weaverName, type) =>
  27. {
  28. // Get the method weaver instance that matches the weaverName
  29. var methodWeaver =
  30. (IHostWeaver<TypeDefinition>)
  31. container.GetService(weaverName, typeof(IHostWeaver<TypeDefinition>));
  32. // Wrap it in a type weaver
  33. var typeWeaver =
  34. (ITypeWeaver) container.GetService("AutoMethodWeaver", typeof(ITypeWeaver), methodWeaver);
  35. var module = type.Module;
  36. if (!typeWeaver.ShouldWeave(type))
  37. return;
  38. // Modify the host module
  39. typeWeaver.ImportReferences(module);
  40. typeWeaver.AddAdditionalMembers(module);
  41. // Weave the type itself
  42. typeWeaver.Weave(type);
  43. };
  44. return result;
  45. }
  46. }
  47. }