From 9b53d77d6b5ab2b99527edb15791fdd5a7b94821 Mon Sep 17 00:00:00 2001 From: Chris Cameron Date: Fri, 15 Jan 2021 11:34:31 -0500 Subject: [PATCH] feat: Added GetOrAddService method for lazy-loading services --- ICD.Common.Utils/Services/ServiceProvider.cs | 25 ++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/ICD.Common.Utils/Services/ServiceProvider.cs b/ICD.Common.Utils/Services/ServiceProvider.cs index 605c02b..25426e2 100644 --- a/ICD.Common.Utils/Services/ServiceProvider.cs +++ b/ICD.Common.Utils/Services/ServiceProvider.cs @@ -25,6 +25,31 @@ namespace ICD.Common.Utils.Services #region Methods + /// + /// Retrieves the registered service of the given type. + /// Creates a new instance using the given function if it does not exist. + /// + /// + /// + /// + [PublicAPI] + [NotNull] + public static TService GetOrAddService([NotNull] Func constructor) + { + if (constructor == null) + throw new ArgumentNullException("constructor"); + + TService output = TryGetService(); + + if (output == null) + { + output = constructor(); + AddService(output); + } + + return output; + } + /// /// Retrieves the registered service of the given type. Use this for required dependencies. ///