feat: Added GetOrAddService method for lazy-loading services

This commit is contained in:
Chris Cameron
2021-01-15 11:34:31 -05:00
parent c1b9426e32
commit 9b53d77d6b

View File

@@ -25,6 +25,31 @@ namespace ICD.Common.Utils.Services
#region Methods #region Methods
/// <summary>
/// Retrieves the registered service of the given type.
/// Creates a new instance using the given function if it does not exist.
/// </summary>
/// <typeparam name="TService"></typeparam>
/// <param name="constructor"></param>
/// <returns></returns>
[PublicAPI]
[NotNull]
public static TService GetOrAddService<TService>([NotNull] Func<TService> constructor)
{
if (constructor == null)
throw new ArgumentNullException("constructor");
TService output = TryGetService<TService>();
if (output == null)
{
output = constructor();
AddService(output);
}
return output;
}
/// <summary> /// <summary>
/// Retrieves the registered service of the given type. Use this for required dependencies. /// Retrieves the registered service of the given type. Use this for required dependencies.
/// </summary> /// </summary>