mirror of
https://github.com/ICDSystems/ICD.Common.Utils.git
synced 2026-01-11 19:44:55 +00:00
feat: Added GetOrAddService method for lazy-loading services
This commit is contained in:
@@ -25,6 +25,31 @@ namespace ICD.Common.Utils.Services
|
||||
|
||||
#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>
|
||||
/// Retrieves the registered service of the given type. Use this for required dependencies.
|
||||
/// </summary>
|
||||
|
||||
Reference in New Issue
Block a user