/src/LinFu.IoC/Interceptors/LazyInterceptor.cs

http://github.com/philiplaureano/LinFu · C# · 63 lines · 35 code · 6 blank · 22 comment · 0 complexity · e1048807682a34dda184fcbf5e6ead2a MD5 · raw file

  1. using System;
  2. using System.Reflection;
  3. using LinFu.AOP.Interfaces;
  4. namespace LinFu.IoC.Interceptors
  5. {
  6. /// <summary>
  7. /// An interceptor class that instantiates a target type only when
  8. /// the methods for that target are invoked.
  9. /// </summary>
  10. /// <typeparam name="T">The type of object to intercept.</typeparam>
  11. public class LazyInterceptor<T> : BaseInterceptor
  12. where T : class
  13. {
  14. private readonly Func<T> _getInstance;
  15. /// <summary>
  16. /// Initializes the class with the <paramref name="getInstance" />
  17. /// factory method.
  18. /// </summary>
  19. /// <param name="getInstance">The functor that will be used to create the actual object instance.</param>
  20. public LazyInterceptor(Func<T> getInstance)
  21. {
  22. _getInstance = getInstance;
  23. }
  24. /// <summary>
  25. /// A method that uses the given factory method to provide a target
  26. /// for the method currently being invoked.
  27. /// </summary>
  28. /// <param name="info">The <see cref="IInvocationInfo" /> object that describes the current invocation context.</param>
  29. /// <returns>The target itself.</returns>
  30. protected override object GetTarget(IInvocationInfo info)
  31. {
  32. return _getInstance();
  33. }
  34. /// <summary>
  35. /// Intercepts the method and initializes the target instance before the
  36. /// actual object is invoked.
  37. /// </summary>
  38. /// <param name="info">The <see cref="IInvocationInfo" /> that describes the execution context.</param>
  39. /// <returns>The return value of the target method.</returns>
  40. public override object Intercept(IInvocationInfo info)
  41. {
  42. var target = _getInstance();
  43. var arguments = info.Arguments;
  44. var method = info.TargetMethod;
  45. object result = null;
  46. try
  47. {
  48. result = method.Invoke(target, arguments);
  49. }
  50. catch (TargetInvocationException ex)
  51. {
  52. throw ex.InnerException;
  53. }
  54. return result;
  55. }
  56. }
  57. }