// ------------------------------------------------------------------------
// Copyright (c) 2021-2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Engine.Services
{
using System;
using System.Collections.Generic;
using Logging;
using Utilities;
///
/// ServiceLocator singleton.
///
public sealed class ServiceLocator : Singleton
{
private ServiceLocator() { } // Hide constructor, use Instance instead.
///
/// Currently registered services.
///
private readonly Dictionary _services = new ();
///
/// Gets the service instance of the given type.
///
/// The type of the service to lookup
/// The service instance
/// Thrown if the service is not registered.
public T Get()
{
if (!_services.ContainsKey(typeof(T)))
{
string error = $"{typeof(T)} is not registered with {GetType().Name}";
EngineLogger.LogError(error);
throw new InvalidOperationException(error);
}
return (T)_services[typeof(T)];
}
///
/// Registers the service with the current service locator.
///
/// Service typ.
/// Service instance
/// Thrown if the service is null.
public void Register(T service)
{
if (service == null) throw new ArgumentNullException(nameof(service));
if (_services.ContainsKey(typeof(T)))
{
EngineLogger.LogWarning($"[{typeof(T)}] is already registered");
return;
}
else
{
EngineLogger.Log($"Service type [{typeof(T)}] registered");
}
_services.Add(typeof(T), service);
}
///
/// Unregisters the service from the current service locator.
///
/// Service type
public void Unregister()
{
if (!_services.ContainsKey(typeof(T)))
{
EngineLogger.LogWarning($"Failed to unregister service since [{typeof(T)}] is not registered yet");
return;
}
else
{
EngineLogger.Log($"Service type [{typeof(T)}] unregistered");
}
_services.Remove(typeof(T));
}
///
/// Get all registered services.
///
public IEnumerable