/src/LinFu.IoC/Interceptors/Redirector.cs

http://github.com/philiplaureano/LinFu · C# · 55 lines · 37 code · 8 blank · 10 comment · 2 complexity · e5929afe654f0b55b5322d9a4fb94c11 MD5 · raw file

  1. using System;
  2. using System.Reflection;
  3. using LinFu.AOP.Interfaces;
  4. using LinFu.IoC.Configuration.Interfaces;
  5. using LinFu.Proxy.Interfaces;
  6. namespace LinFu.IoC.Interceptors
  7. {
  8. /// <summary>
  9. /// An interceptor class that redirects calls to another interceptor.
  10. /// </summary>
  11. internal class Redirector : BaseInterceptor
  12. {
  13. private readonly Func<object> _getActualTarget;
  14. private readonly IInterceptor _interceptor;
  15. private readonly IProxyFactory _proxyFactory;
  16. public Redirector(Func<object> getActualTarget, IInterceptor targetInterceptor, IProxyFactory factory,
  17. IMethodInvoke<MethodInfo> methodInvoke)
  18. : base(methodInvoke)
  19. {
  20. _getActualTarget = getActualTarget;
  21. _interceptor = targetInterceptor;
  22. _proxyFactory = factory;
  23. }
  24. public override object Intercept(IInvocationInfo info)
  25. {
  26. // Instead of using the proxy as the target,
  27. // modify the InvocationInfo to show the actual target
  28. var proxyType = _proxyFactory.CreateProxyType(typeof(IInvocationInfo), new Type[0]);
  29. var infoProxy = Activator.CreateInstance(proxyType) as IProxy;
  30. if (infoProxy == null)
  31. return base.Intercept(info);
  32. var modifiedInfo = (IInvocationInfo) infoProxy;
  33. // Replace the proxy target with the actual target
  34. var infoInterceptor = new InvocationInfoInterceptor(info, _getActualTarget, MethodInvoker);
  35. infoProxy.Interceptor = infoInterceptor;
  36. return _interceptor.Intercept(modifiedInfo);
  37. }
  38. /// <summary>
  39. /// Gets the target object instance.
  40. /// </summary>
  41. /// <param name="info">The <see cref="IInvocationInfo" /> instance that describes the current execution context.</param>
  42. protected override object GetTarget(IInvocationInfo info)
  43. {
  44. return _getActualTarget();
  45. }
  46. }
  47. }