PageRenderTime 41ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/src/LinFu.AOP.Interfaces/TypeActivatorRegistry.cs

http://github.com/philiplaureano/LinFu
C# | 51 lines | 28 code | 7 blank | 16 comment | 9 complexity | 6198a29ca443fb0e7d263c23b8b4935a MD5 | raw file
  1. using System;
  2. namespace LinFu.AOP.Interfaces
  3. {
  4. /// <summary>
  5. /// Represents a registry that allows users to statically register <see cref="ITypeActivator" />
  6. /// instances.
  7. /// </summary>
  8. public static class TypeActivatorRegistry
  9. {
  10. private static readonly object _lock = new object();
  11. private static ITypeActivator _activator;
  12. /// <summary>
  13. /// Obtains an activator for the given <paramref name="context" />.
  14. /// </summary>
  15. /// <param name="context">The <see cref="ITypeActivationContext" /> instance that describes the object to be created.</param>
  16. /// <returns>A method activator.</returns>
  17. public static ITypeActivator GetActivator(ITypeActivationContext context)
  18. {
  19. if (context == null)
  20. throw new ArgumentNullException("context");
  21. // Use the static activator by default
  22. var currentActivator = _activator;
  23. // Use the activator attached to the target if it exists
  24. var host = context.Target as IActivatorHost;
  25. if (host != null && host.Activator != null)
  26. currentActivator = host.Activator;
  27. if (currentActivator != null && currentActivator.CanActivate(context))
  28. return currentActivator;
  29. return null;
  30. }
  31. /// <summary>
  32. /// Sets the <see cref="ITypeActivator" /> that will be used to
  33. /// instantiate object instances.
  34. /// </summary>
  35. /// <param name="activator">The <see cref="ITypeActivator" /> that will instantiate types.</param>
  36. public static void SetActivator(ITypeActivator activator)
  37. {
  38. lock (_lock)
  39. {
  40. _activator = activator;
  41. }
  42. }
  43. }
  44. }