-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServiceLocator.cs
More file actions
89 lines (74 loc) · 2.08 KB
/
ServiceLocator.cs
File metadata and controls
89 lines (74 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public interface IGameService
{
}
public static class ServiceLocator
{
static readonly Dictionary<Type, object> services = new();
public static T Get<T>()
{
var key = typeof(T);
if (!services.ContainsKey(key))
{
Debug.LogError($"{key} not registered");
return default;
}
return (T)services[key];
}
public static bool TryGet<T>(out T result)
{
result = default;
var key = typeof(T);
if (!services.TryGetValue(key, out var r))
return false;
result = (T)r;
return true;
}
public static void Register(object service)
{
Register(service.GetType(), service);
var interfaces = service.GetType().GetInterfaces();
foreach (var t in interfaces)
if (typeof(IGameService).IsAssignableFrom(t) && t != typeof(IGameService))
Register(t, service);
}
public static void Register(Type type, object service)
{
if (services.ContainsKey(type))
{
Debug.LogError($"Attempted to register service of type {type} which is already registered.");
return;
}
services.Add(type, service);
}
public static void Unregister(object service)
{
var registeredTypes = services.Where(kvp => kvp.Value == service)
.Select(kvp => kvp.Key).ToList();
foreach (var t in registeredTypes)
{
Unregister(t);
}
}
public static void Unregister<T>()
{
Unregister(typeof(T));
}
private static void Unregister(Type type)
{
if (!services.ContainsKey(type))
{
Debug.LogError($"Attempted to unregister service of type {type} which is not registered.");
return;
}
services.Remove(type);
}
public static void Clear()
{
services.Clear();
}
public static IReadOnlyDictionary<Type, object> AllInstalledServices => services;
}