Skip to content

Service Locator

Stanislav Osipov edited this page Oct 17, 2020 · 1 revision

The service locator pattern is a design pattern used in software development to encapsulate the processes involved in obtaining a service with a strong abstraction layer.

Long story short it just gives you a simple way to decouple dependencies. There are a lot of pros and cons about this pattern but it's up to you to decide if this pattern fits your project. Few articles we think it worth reading before using this pattern.

How to use:

Feel free to explore API Documentation.

But it pretty much comes down to Register and Unregister For example here is how you can register some services in it:

public static class App
{
	static readonly ServiceLocator s_Services = new ServiceLocator();

	internal static void Init(Action onComplete)
	{
	    var sceneService = new DefaultSceneLoadService();
	    s_Services.Register<ISceneService>(sceneService);
	    s_Services.Register<IPoolingService>(new GameObjectsPool("GameObjects Pool"));
	}
}

There is also an IReadOnlyServiceLocator interface that lets you hide the ability to register new services. So the complete implementation would look like:

public static class App
{
	static readonly ServiceLocator s_Services = new ServiceLocator();
        public static IReadOnlyServiceLocator Services => s_Services;

	internal static void Init(Action onComplete)
	{
	    var sceneService = new DefaultSceneLoadService();
	    s_Services.Register<ISceneService>(sceneService);
	    s_Services.Register<IPoolingService>(new GameObjectsPool("GameObjects Pool"));
	}
}

And now it's super easy to get retrieve a service from the locator:

var pool = App.Services.Get<IPoolingService>();

Clone this wiki locally