Service Injection 101
Here is a quick showcase of how a service can be injected to a component:
Service.cs:
using Sisus.Init; using UnityEngine; [Service] class Service { public void Greet() => Debug.Log("Hello, World!"); }
Client.cs:
using Sisus.Init; class Client : MonoBehaviour<Service> { protected override void Init(Service service) => service.Greet(); }
- Create script files from the two snippets of code above.
- Attach the Client component to a GameObject in a scene
- Enter Play Mode.
You should see “Hello, World!” printed in the Console window.
How It Works
When the game is launching, Init(args) finds all types in the project that have the [Service] attribute, and creates and caches a single instance out of each one. This takes places just before the first scene is loaded.
When a component that derives from a MonoBehaviour<T…> class is being loaded, and all generic arguments of its base class are service types, then the component will automatically receive instances of those services in its Init function.
Since the Service class has the [Service] attribute, and single instance of it is created right before the first scene is loaded, and because Client derives from MonoBehaviour<T…>, it automatically receives a reference to the service when it is being loaded.
Usually a component would use the Init function just to assign all the received objects into member variables, and then all the actual work where those services are used would take place in other methods, such as Start or Update. However for the sake of brevity in the above example the Client just immediately invokes the Greet method in the Service object, causing the “Hello, World!” text to get printed.
Note: if not all Init arguments of a component are services, then an Initializer can be used to specify the rest of the injected arguments.