mirror of
https://github.com/ICDSystems/ICD.Common.Utils.git
synced 2026-04-12 20:17:15 +00:00
Added "TryAddService" methods to fail gracefully if service already exists
This commit is contained in:
parent
4f46a3ebda
commit
5ab9d43c38
1 changed files with 63 additions and 0 deletions
|
|
@ -132,6 +132,21 @@ namespace ICD.Common.Services
|
|||
AddService(typeof(TService), service);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers a service instance to the type given.
|
||||
/// </summary>
|
||||
/// <typeparam name="TService"></typeparam>
|
||||
/// <param name="service"></param>
|
||||
[PublicAPI]
|
||||
public static bool TryAddService<TService>(TService service)
|
||||
{
|
||||
// ReSharper disable once CompareNonConstrainedGenericWithNull
|
||||
if (service == null)
|
||||
throw new ArgumentNullException("service");
|
||||
|
||||
return TryAddService(typeof(TService), service);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers a service instance to the type given.
|
||||
/// </summary>
|
||||
|
|
@ -149,6 +164,23 @@ namespace ICD.Common.Services
|
|||
Instance.AddServiceInstance(tService, service);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers a service instance to the type given.
|
||||
/// </summary>
|
||||
/// <param name="tService"></param>
|
||||
/// <param name="service"></param>
|
||||
[PublicAPI]
|
||||
public static bool TryAddService(Type tService, object service)
|
||||
{
|
||||
if (tService == null)
|
||||
throw new ArgumentNullException("tService");
|
||||
|
||||
if (service == null)
|
||||
throw new ArgumentNullException("service");
|
||||
|
||||
return Instance.TryAddServiceInstance(tService, service);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Attempts to remove the given service from the given type.
|
||||
/// </summary>
|
||||
|
|
@ -259,6 +291,37 @@ namespace ICD.Common.Services
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds the given service under the given type.
|
||||
/// </summary>
|
||||
/// <param name="tService"></param>
|
||||
/// <param name="service"></param>
|
||||
private bool TryAddServiceInstance(Type tService, object service)
|
||||
{
|
||||
if (tService == null)
|
||||
throw new ArgumentNullException("tService");
|
||||
|
||||
if (service == null)
|
||||
throw new ArgumentNullException("service");
|
||||
|
||||
try
|
||||
{
|
||||
m_ServicesSection.Enter();
|
||||
|
||||
if (m_Services.ContainsKey(tService))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
m_Services.Add(tService, service);
|
||||
}
|
||||
finally
|
||||
{
|
||||
m_ServicesSection.Leave();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the given service from the given type.
|
||||
/// </summary>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue