Service Locator Alternative
using System;
using System.Collections;
using System.Collections.Generic;
using UniFlux;
using UnityEngine;
public class ServiceLocator
{
private static readonly Dictionary<Type, object> services = new Dictionary<Type, object>();
public static void RegisterService<T>(T service)
{
var type = typeof(T); // Look here, typeof causing garbage
if (!services.ContainsKey(type))
{
services.Add(type, service);
}
}
public static T GetService<T>()
{
var type = typeof(T); // Look here, typeof causing garbage
if (services.ContainsKey(type))
{
return (T)services[type]; // look here, (T) making explicit convertions
}
throw new Exception($"Service of type {type} not registered.");
}
}
class Example_A : Monobehaviour, IDataService
{
void Awake()
{
// Generate
ServiceLocator.RegisterService<IDataService>(this);
}
void IDataService.SaveData(string data)
{
// etc...
}
}
class Example_B : Monobehaviour
{
void Start()
{
// Getting the instances..
var dataService = ServiceLocator.GetService<IDataService>();
// Using it
dataService.SaveData("Sample data");
}
}Last updated