File tree Expand file tree Collapse file tree 2 files changed +14
-19
lines changed
Assets/Creational/ServiceLocator/Scripts Expand file tree Collapse file tree 2 files changed +14
-19
lines changed Original file line number Diff line number Diff line change @@ -13,28 +13,12 @@ public interface IService
13
13
public static class ServiceLocator
14
14
{
15
15
private static readonly Dictionary < Type , object > _registry = new Dictionary < Type , object > ( ) ;
16
- public static bool IsInitialized { get ; private set ; }
17
-
18
- public static void InitializeServices ( )
19
- {
20
- var logger = new ServiceLogger ( ) ;
21
-
22
- //Note: the binding happens with the interface.
23
- RegisterService < ILogger > ( logger ) ;
24
- RegisterService < IAudioPlayer > ( new ServiceAudio ( ) ) ;
25
- RegisterService < IAchievements > ( new ServiceAchievements ( ) ) ;
26
- IsInitialized = true ;
27
- logger . Log ( "Services" , "Initialized successfully" ) ;
28
- }
29
16
30
17
/// <summary>
31
18
/// Returns null in case the service is not registered or services not initialized.
32
19
/// </summary>
33
20
public static T GetService < T > ( ) where T : class
34
21
{
35
- if ( ! IsInitialized )
36
- return null ;
37
-
38
22
var type = typeof ( T ) ;
39
23
var containsService = _registry . ContainsKey ( type ) ;
40
24
return containsService ? _registry [ type ] as T : null ;
@@ -43,7 +27,7 @@ public static T GetService<T>() where T : class
43
27
/// <summary>
44
28
/// Registers a service in the list.
45
29
/// </summary>
46
- private static void RegisterService < T > ( IService service ) where T : IService
30
+ public static void RegisterService < T > ( IService service ) where T : IService
47
31
{
48
32
var type = typeof ( T ) ;
49
33
_registry [ type ] = service ;
Original file line number Diff line number Diff line change 2
2
3
3
namespace ServiceLocatorExample
4
4
{
5
+ /// <summary>
6
+ /// Passes all the necessary services.
7
+ /// </summary>
5
8
public class ServicesInitializer : MonoBehaviour
6
9
{
7
10
private void Awake ( )
8
11
{
9
- //First thing to do
10
- ServiceLocator . InitializeServices ( ) ;
12
+ var logger = new ServiceLogger ( ) ;
13
+ var audioPlayer = new ServiceAudio ( ) ;
14
+ var achievements = new ServiceAchievements ( ) ;
15
+
16
+ //Note: the binding happens with the interface.
17
+ ServiceLocator . RegisterService < ILogger > ( logger ) ;
18
+ ServiceLocator . RegisterService < IAudioPlayer > ( audioPlayer ) ;
19
+ ServiceLocator . RegisterService < IAchievements > ( achievements ) ;
20
+
21
+ logger . Log ( "Services" , "Initialized successfully" ) ;
11
22
}
12
23
}
13
24
}
You can’t perform that action at this time.
0 commit comments