/src/LinFu.IoC/Interceptors/ProxyInjector.cs

http://github.com/philiplaureano/LinFu · C# · 56 lines · 30 code · 8 blank · 18 comment · 5 complexity · 34a70ab52eadb9b321f7c6a4bbdccc7d MD5 · raw file

  1. using System;
  2. using LinFu.IoC.Interfaces;
  3. using LinFu.Proxy.Interfaces;
  4. namespace LinFu.IoC.Interceptors
  5. {
  6. /// <summary>
  7. /// Represents a class that automatically injects a proxy instance
  8. /// instead of an actual service instance.
  9. /// </summary>
  10. public class ProxyInjector : IPostProcessor
  11. {
  12. private readonly Func<IServiceRequestResult, object> _createProxy;
  13. private readonly Func<IServiceRequestResult, bool> _filterPredicate;
  14. /// <summary>
  15. /// Initializes the class with the <paramref name="filterPredicate" />
  16. /// and the <paramref name="createProxy" /> factory method.
  17. /// </summary>
  18. /// <param name="filterPredicate">The predicate that will determine which service requests will be proxied.</param>
  19. /// <param name="createProxy">The factory method that will generate the proxy instance itself.</param>
  20. public ProxyInjector(Func<IServiceRequestResult, bool> filterPredicate,
  21. Func<IServiceRequestResult, object> createProxy)
  22. {
  23. _filterPredicate = filterPredicate;
  24. _createProxy = createProxy;
  25. }
  26. /// <summary>
  27. /// A method that injects service proxies in place of the actual <see cref="IServiceRequestResult.ActualResult" />.
  28. /// </summary>
  29. /// <param name="result">The <see cref="IServiceRequestResult" /> instance that describes the service request.</param>
  30. public void PostProcess(IServiceRequestResult result)
  31. {
  32. if (!_filterPredicate(result))
  33. return;
  34. var container = result.Container;
  35. var hasProxyFactory = container.Contains(typeof(IProxyFactory));
  36. // Inject proxies only if a
  37. // proxy factory instance is available
  38. if (!hasProxyFactory)
  39. return;
  40. // Sealed types cannot be intercepted
  41. var serviceType = result.ServiceType;
  42. if (result.ActualResult != null && serviceType.IsSealed)
  43. return;
  44. // Replace the actual result with the proxy itself
  45. result.ActualResult = _createProxy(result);
  46. }
  47. }
  48. }