The package is available on the openupm registry. It's recommended to install it via openupm-cli.
openupm add com.apollo.servicelocator
Since Unity 2019.3, use Add a package from git URL button from the Package Manager UI to install the package.
https://github.com/hajimeku/ServiceLocator.git
For previous Unity versions, add the following line to the project manifest.json file.
{
"dependencies": {
"com.apollo.servicelocator": "https://github.com/hajimeku/ServiceLocator.git"
}
}
This is a very lightweight Service Locator Pattern library that is intended to help facilitate structure and support for Unit Testing without the need of heavy libraries such as DI.
You can register a service like this:
//For Regular Classes
ServiceLocatorManager.Instance.Register<IExampleRegularClass>(new ExampleRegularClass());
//For Monobehaviour classes
ServiceLocatorManager.Instance.Register<IExampleMonobehaviourClass>(ServiceLocatorManager.AsMono<ExampleMonobehaviourClass>());
To fetch a service you can request it like this:
private IExampleRegularClass regularClass => ServiceLocatorManager.Instance.Resolve<IExampleRegularClass>();
private IExampleMonobehaviourClass monobehaviourClass => ServiceLocatorManager.Instance.Resolve<IExampleMonobehaviourClass>();
Example Bootstrap Class. Make sure to create one of these and register your services on a static function marked like ConfigureServices
public static class ExampleBootstrap
{
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
public static void ConfigureServices()
{
//Register this for debug log
ServiceLocatorManager.Instance.Register<IExampleLog>(new ExampleProductionLog());
//Register this for a Debug log
//ServiceLocatorManager.Instance.Register<IExampleLog>(new ExampleDebugLog());
}
}