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
1313 public static class ServiceLocator
1414 {
1515 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- }
2916
3017 /// <summary>
3118 /// Returns null in case the service is not registered or services not initialized.
3219 /// </summary>
3320 public static T GetService < T > ( ) where T : class
3421 {
35- if ( ! IsInitialized )
36- return null ;
37-
3822 var type = typeof ( T ) ;
3923 var containsService = _registry . ContainsKey ( type ) ;
4024 return containsService ? _registry [ type ] as T : null ;
@@ -43,7 +27,7 @@ public static T GetService<T>() where T : class
4327 /// <summary>
4428 /// Registers a service in the list.
4529 /// </summary>
46- private static void RegisterService < T > ( IService service ) where T : IService
30+ public static void RegisterService < T > ( IService service ) where T : IService
4731 {
4832 var type = typeof ( T ) ;
4933 _registry [ type ] = service ;
Original file line number Diff line number Diff line change 22
33namespace ServiceLocatorExample
44{
5+ /// <summary>
6+ /// Passes all the necessary services.
7+ /// </summary>
58 public class ServicesInitializer : MonoBehaviour
69 {
710 private void Awake ( )
811 {
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" ) ;
1122 }
1223 }
1324}
You can’t perform that action at this time.
0 commit comments