/src/LinFu.IoC/Interceptors/InvocationInfoInterceptor.cs

http://github.com/philiplaureano/LinFu · C# · 63 lines · 36 code · 8 blank · 19 comment · 4 complexity · 35da634cd8e96c41bf7d8b3ac718ba50 MD5 · raw file

  1. using System;
  2. using System.Reflection;
  3. using LinFu.AOP.Interfaces;
  4. using LinFu.IoC.Configuration.Interfaces;
  5. namespace LinFu.IoC.Interceptors
  6. {
  7. /// <summary>
  8. /// An interceptor that intercepts <see cref="IInvocationInfo" /> instances
  9. /// and replaces the original target instance with a surrogate instance.
  10. /// </summary>
  11. internal class InvocationInfoInterceptor : BaseInterceptor
  12. {
  13. private static readonly MethodInfo _targetMethod;
  14. private readonly Func<object> _getActualTarget;
  15. private readonly IInvocationInfo _realInfo;
  16. static InvocationInfoInterceptor()
  17. {
  18. var targetProperty = typeof(IInvocationInfo).GetProperty("Target");
  19. _targetMethod = targetProperty.GetGetMethod();
  20. }
  21. /// <summary>
  22. /// Initializes the class with a functor that can provide the actual target instance.
  23. /// </summary>
  24. /// <param name="getActualTarget">
  25. /// The <see cref="Func{TResult}" /> that will provide the target instance that will be used
  26. /// for the method invocation.
  27. /// </param>
  28. /// <param name="methodInvoke">The method invoker.</param>
  29. /// <param name="realInfo">The <see cref="IInvocationInfo" /> instance that describes the current execution context.</param>
  30. internal InvocationInfoInterceptor(IInvocationInfo realInfo, Func<object> getActualTarget,
  31. IMethodInvoke<MethodInfo> methodInvoke) : base(methodInvoke)
  32. {
  33. _getActualTarget = getActualTarget;
  34. _realInfo = realInfo;
  35. }
  36. public override object Intercept(IInvocationInfo info)
  37. {
  38. var targetMethod = info.TargetMethod;
  39. // Intercept calls made only to the IInvocationInfo interface
  40. if (targetMethod.DeclaringType != typeof(IInvocationInfo) || targetMethod.Name != "get_Target")
  41. return base.Intercept(info);
  42. var target = _getActualTarget();
  43. // Replace the proxy with the actual target
  44. return target;
  45. }
  46. /// <summary>
  47. /// Gets the target object instance.
  48. /// </summary>
  49. /// <param name="info">The <see cref="IInvocationInfo" /> instance that describes the current execution context.</param>
  50. protected override object GetTarget(IInvocationInfo info)
  51. {
  52. return _realInfo;
  53. }
  54. }
  55. }