36 lines
925 B
C#
36 lines
925 B
C#
using System.Collections.Generic;
|
|
using System;
|
|
using log4net;
|
|
using System.Reflection;
|
|
public static class Locator
|
|
{
|
|
private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
|
|
private static readonly Dictionary<Type, object> services = new();
|
|
public static void RegisterService<T>(T service)
|
|
{
|
|
Type serviceType = typeof(T);
|
|
if (!services.ContainsKey(serviceType))
|
|
{
|
|
services.Add(serviceType, service);
|
|
}
|
|
else
|
|
{
|
|
Log.Warn($"Service of type {serviceType} is alreade registered.");
|
|
}
|
|
}
|
|
|
|
public static T GetService<T>()
|
|
{
|
|
Type serviceType = typeof(T);
|
|
if (services.TryGetValue(serviceType, out var service))
|
|
{
|
|
return (T)service;
|
|
}
|
|
else
|
|
{
|
|
Log.Error($"Service of type {serviceType} not registered.using System.Collections");
|
|
throw new KeyNotFoundException($"Service of type {serviceType} not registered.using System.Collections");
|
|
}
|
|
}
|
|
}
|