/src/LinFu.AOP.Interfaces/BootStrapRegistry.cs

http://github.com/philiplaureano/LinFu · C# · 71 lines · 47 code · 9 blank · 15 comment · 1 complexity · 3bfec87fd9665c006ae57bf92453ff31 MD5 · raw file

  1. using System;
  2. using System.Collections.Generic;
  3. using LinFu.Reflection;
  4. namespace LinFu.AOP.Interfaces
  5. {
  6. /// <summary>
  7. /// Represents a registry class that bootstraps components into memory when the application starts.
  8. /// </summary>
  9. public sealed class BootStrapRegistry
  10. {
  11. private readonly IList<IBootStrappedComponent> _components = new List<IBootStrappedComponent>();
  12. private BootStrapRegistry()
  13. {
  14. Initialize();
  15. }
  16. /// <summary>
  17. /// Gets the value indicating the BootStrapRegistry instance.
  18. /// </summary>
  19. public static BootStrapRegistry Instance => NestedLoader.Instance;
  20. /// <summary>
  21. /// Initializes the BootStrapRegistry.
  22. /// </summary>
  23. private void Initialize()
  24. {
  25. lock (_components)
  26. {
  27. _components.LoadFrom(AppDomain.CurrentDomain.BaseDirectory, "*.dll");
  28. foreach (var component in _components)
  29. try
  30. {
  31. component.Initialize();
  32. }
  33. catch (Exception ex)
  34. {
  35. var componentName = component != null ? component.GetType().Name : "(unknown)";
  36. var message = string.Format("{0} Error: Unable to load component '{1}' - {2}",
  37. GetType().FullName,
  38. componentName, ex);
  39. throw new BootstrapException(message, ex);
  40. }
  41. }
  42. }
  43. /// <summary>
  44. /// Returns the list of components that have been initialized by the bootstrapper.
  45. /// </summary>
  46. /// <returns></returns>
  47. public IEnumerable<IBootStrappedComponent> GetComponents()
  48. {
  49. return _components;
  50. }
  51. private class NestedLoader
  52. {
  53. internal static readonly BootStrapRegistry Instance;
  54. // Explicit static constructor to tell C# compiler
  55. // not to mark type as beforefieldinit
  56. static NestedLoader()
  57. {
  58. Instance = new BootStrapRegistry();
  59. }
  60. }
  61. }
  62. }