Added "TryAddService" methods to fail gracefully if service already exists

This commit is contained in:
Drew Tingen
2017-11-17 13:50:32 -05:00
parent 4f46a3ebda
commit 5ab9d43c38

View File

@@ -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>