/src/LinFu.Proxy.Extensions/ObjectExtensions.cs

http://github.com/philiplaureano/LinFu · C# · 52 lines · 28 code · 5 blank · 19 comment · 0 complexity · 1879733d88bcb9622e1ec5c2530746fb MD5 · raw file

  1. using System;
  2. using LinFu.IoC;
  3. using LinFu.IoC.Interfaces;
  4. using LinFu.IoC.Reflection;
  5. using LinFu.Proxy.Interfaces;
  6. namespace LinFu.Proxy
  7. {
  8. /// <summary>
  9. /// A class that adds proxy support to the <see cref="object" /> class
  10. /// </summary>
  11. public static class ObjectExtensions
  12. {
  13. private static readonly IServiceContainer _container = new ServiceContainer();
  14. static ObjectExtensions()
  15. {
  16. _container.LoadFromBaseDirectory("*.dll");
  17. }
  18. /// <summary>
  19. /// Creates a duck type that redirects its calls to the
  20. /// given <paramref name="target" />.
  21. /// </summary>
  22. /// <param name="target">The target instance that will be invoked once the duck type instance has been invoked.</param>
  23. /// <param name="baseInterfaces">The additional list of interfaces that will be implemented by the duck type.</param>
  24. /// <typeparam name="T">The type parameter that describes the duck type.</typeparam>
  25. /// <returns>The return value from the target method.</returns>
  26. public static T CreateDuck<T>(this object target, params Type[] baseInterfaces)
  27. {
  28. return (T) target.CreateDuck(typeof(T), baseInterfaces);
  29. }
  30. /// <summary>
  31. /// Creates a duck type that redirects its calls to the
  32. /// given <paramref name="target" />.
  33. /// </summary>
  34. /// <param name="target">The target instance that will be invoked once the duck type instance has been invoked.</param>
  35. /// <param name="duckType">The <see cref="System.Type" /> that describes the duck type.</param>
  36. /// <param name="baseInterfaces">The additional list of interfaces that will be implemented by the duck type.</param>
  37. /// <returns>The return value from the target method.</returns>
  38. public static object CreateDuck(this object target, Type duckType, params Type[] baseInterfaces)
  39. {
  40. Func<string, Type[], object[], object> implementation
  41. = (methodName, typeArguments, arguments) =>
  42. target.Invoke(methodName, typeArguments, arguments);
  43. var proxyFactory = _container.GetService<IProxyFactory>();
  44. return proxyFactory.CreateProxy(duckType, implementation, baseInterfaces);
  45. }
  46. }
  47. }