From a0138af362be2f4640ccb326f715dc1dd1ae3760 Mon Sep 17 00:00:00 2001 From: Bjarke Berg Date: Wed, 6 Nov 2019 10:56:11 +0100 Subject: [PATCH] Move a small part of current --- src/Umbraco.Abstractions/Composing/Current.cs | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 src/Umbraco.Abstractions/Composing/Current.cs diff --git a/src/Umbraco.Abstractions/Composing/Current.cs b/src/Umbraco.Abstractions/Composing/Current.cs new file mode 100644 index 0000000000..39a7f5c8be --- /dev/null +++ b/src/Umbraco.Abstractions/Composing/Current.cs @@ -0,0 +1,58 @@ +using System; +using Umbraco.Core.Logging; + +namespace Umbraco.Core.Composing +{ + /// + /// Provides a static service locator for most singletons. + /// + /// + /// This class is initialized with the container in UmbracoApplicationBase, + /// right after the container is created in UmbracoApplicationBase.HandleApplicationStart. + /// Obviously, this is a service locator, which some may consider an anti-pattern. And yet, + /// practically, it works. + /// + public static class CurrentCore + { + private static IFactory _factory; + + private static ILogger _logger; + private static IProfiler _profiler; + private static IProfilingLogger _profilingLogger; + + /// + /// Gets or sets the factory. + /// + public static IFactory Factory + { + get + { + if (_factory == null) throw new InvalidOperationException("No factory has been set."); + return _factory; + } + set + { + if (_factory != null) throw new InvalidOperationException("A factory has already been set."); + // if (_configs != null) throw new InvalidOperationException("Configs are unlocked."); + _factory = value; + } + } + + internal static bool HasFactory => _factory != null; + + #region Getters + + public static ILogger Logger + => _logger ?? (_logger = _factory?.TryGetInstance() ?? throw new Exception("TODO Fix")); //?? new DebugDiagnosticsLogger(new MessageTemplates())); + + public static IProfiler Profiler + => _profiler ?? (_profiler = _factory?.TryGetInstance() + ?? new LogProfiler(Logger)); + + public static IProfilingLogger ProfilingLogger + => _profilingLogger ?? (_profilingLogger = _factory?.TryGetInstance()) + ?? new ProfilingLogger(Logger, Profiler); + + #endregion + } +}