/src/LinFu.IoC/Factories/DelegateFactory.cs

http://github.com/philiplaureano/LinFu · C# · 58 lines · 36 code · 8 blank · 14 comment · 4 complexity · a368d553114cfeb4706f636e56c25114 MD5 · raw file

  1. using System;
  2. using System.Linq;
  3. using System.Reflection;
  4. using LinFu.IoC.Interfaces;
  5. namespace LinFu.IoC.Factories
  6. {
  7. /// <summary>
  8. /// Represents a class that uses a <see cref="MulticastDelegate" />
  9. /// to instantiate a service instance.
  10. /// </summary>
  11. public class DelegateFactory : IFactory
  12. {
  13. private readonly MulticastDelegate _targetDelegate;
  14. /// <summary>
  15. /// Initializes the class with the given <paramref name="targetDelegate" />
  16. /// </summary>
  17. /// <param name="targetDelegate">The delegate that will be used to instantiate the factory.</param>
  18. public DelegateFactory(MulticastDelegate targetDelegate)
  19. {
  20. if (targetDelegate.Method.ReturnType == typeof(void))
  21. throw new ArgumentException("The factory delegate must have a return type.");
  22. _targetDelegate = targetDelegate;
  23. }
  24. /// <summary>
  25. /// Instantiates the service type using the given delegate.
  26. /// </summary>
  27. /// <param name="request">The <see cref="IFactoryRequest" /> that describes the service that needs to be created.</param>
  28. /// <returns>The service instance.</returns>
  29. public object CreateInstance(IFactoryRequest request)
  30. {
  31. object result = null;
  32. try
  33. {
  34. var target = _targetDelegate.Target;
  35. var method = _targetDelegate.Method;
  36. var argCount = request.Arguments.Length;
  37. var methodArgCount = method.GetParameters().Count();
  38. if (argCount != methodArgCount)
  39. throw new ArgumentException("Parameter Count Mismatch");
  40. result = _targetDelegate.DynamicInvoke(request.Arguments);
  41. }
  42. catch (TargetInvocationException ex)
  43. {
  44. // Unroll the exception
  45. throw ex.InnerException;
  46. }
  47. return result;
  48. }
  49. }
  50. }