Services with dependency injection
A service is a shared object your game needs in many places, such as a high score, an inventory or a save file. Instead of looking it up through a global, you register it once and Turian hands it to every component that declares it. This tutorial takes about fifteen minutes. You need to have finished the getting-started tutorial, which covers creating a project, writing a script and Play Mode.
1. Create a project
turian-cli new ServicesDemo
turian-studio --project ServicesDemo
The new project has the starter scene Assets/scene-01.prefab, with a Camera, a Light and a Box. It also has Assets/Game.cs, which declares the Usercode.Game type. Turian uses that type to find your project's assembly, so leave the file in place.
2. Write a service module
Create Assets/Services/GameServices.cs:
using Microsoft.Extensions.DependencyInjection;
namespace Usercode;
public sealed class GameServices : IEngineServiceModule
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSubsystem(LifetimeScope.Application, static _ => new Highscores());
services.AddSubsystem(LifetimeScope.Session,
static scope => new Scoreboard(scope.Get<Highscores>()), typeof(Highscores));
services.AddSubsystem(LifetimeScope.Scene, static _ => new Pickups());
}
}
Turian calls ConfigureServices on every class in your project that implements IEngineServiceModule. Such a class needs a public parameterless constructor, which is the default when you write none. Each AddSubsystem call registers one service together with the lifetime scope that owns it. The typeof(Highscores) argument declares a dependency: the scoreboard is created after the high score and stops before it.
3. Define the services
Create Assets/Services/Scores.cs:
namespace Usercode;
/// <summary>The best score seen so far, kept for as long as the game runs.</summary>
public sealed class Highscores : ISubsystem
{
public int Best { get; private set; }
public void Record(int points) => Best = Math.Max(Best, points);
public void Start() { }
public void Stop() { }
}
/// <summary>The points of the current session. A session restart sets them back to zero.</summary>
public sealed class Scoreboard(Highscores highscores) : ISubsystem
{
public int Points { get; private set; }
public void Add(int amount)
{
Points += amount;
highscores.Record(Points);
}
public void Start() { }
public void Stop() { }
}
/// <summary>The pickups collected in the loaded scene. Loading another scene starts them from zero.</summary>
public sealed class Pickups : ISubsystem
{
public int Collected { get; private set; }
public void Collect() => Collected++;
public void Start() { }
public void Stop() { }
}
Every service that owns a lifecycle implements ISubsystem. Turian calls Start on the main thread once the subsystems it depends on have started, and calls Stop before they stop. These three services have no resources to set up, so their methods are empty.
4. Inject the services into a component
Create Assets/Collector.cs:
using System.Text.Json.Serialization;
namespace Usercode;
/// <summary>Scores a pickup when Space is pressed, and restarts the session when R is pressed.</summary>
public class Collector : Component
{
[InjectService, JsonIgnore]
public Scoreboard? Scoreboard { get; private set; }
[InjectService, JsonIgnore]
public Highscores? Highscores { get; private set; }
[InjectService, JsonIgnore]
public ISessionLifetime? Lifetimes { get; private set; }
[InjectService, JsonIgnore]
public IInputSource? Input { get; private set; }
public override void OnUpdate(float deltaTime)
{
if (Input is null || Scoreboard is null || Highscores is null || Lifetimes is null) return;
if (Input.WasKeyPressed(Key.Space))
{
Scoreboard.Add(10);
var pickups = Lifetimes.SceneOf(Node!)?.Get<Pickups>();
pickups?.Collect();
Log.Logger.LogInformation("Points {Points}, pickups in this scene {Pickups}",
Scoreboard.Points, pickups?.Collected);
}
if (Input.WasKeyPressed(Key.R))
{
Log.Logger.LogInformation("Best so far {Best}", Highscores.Best);
Lifetimes.Restart();
}
}
}
Select Box in the Scene Tree, click Add Component in the Inspector and choose Collector. Save the scene with Ctrl+S.
Turian fills every [InjectService] property before the component's OnAwake, so the properties are ready in the lifecycle callbacks. Each property type is looked up as a registered service. Scoreboard and Highscores are session and application subsystems, so the component receives the live instances. A property must have a setter and carry [JsonIgnore], so the injected object is never written into the scene file. If a required service is not registered, Turian reports an error that names the missing type before the component's callbacks run. Add Optional = true to the attribute to allow a null value instead.
Scene subsystems are not injected this way. To reach one, ask ISessionLifetime for the scope of the scene that holds the node, as Collector does with SceneOf(Node!).
5. Choose a lifetime
| Scope | Lives until | Survives a scene load | Use it for |
|---|---|---|---|
LifetimeScope.Application |
the game stops | yes | a high score, settings, a save service |
LifetimeScope.Session |
the session ends: a restart, or the game stops | yes | the current run's score, the inventory |
LifetimeScope.Scene |
the scene unloads | no | anything that belongs to one level |
Pick the shortest lifetime that still covers every user of the service. A scene-scoped service is recreated each time its scene loads, and a session-scoped service can read an application-scoped one, but not the other way around.
A plain class with no start or stop work does not need a scope. Register it with services.AddSingleton<TService, TImplementation>() in the same module, and [InjectService] finds it the same way. It exists for the whole run of the game and is not rebuilt when a session restarts.
6. Play
Press F5, then click inside the Game view so it receives the keyboard. Press Space three times. The Output panel, which is where log messages appear, shows Points 10, pickups in this scene 1, then 20 and 2, then 30 and 3.
Press R. The output shows Best so far 30, the session restarts, and the scene reloads. Press Space once more: the points start again at 10, and the pickups count is 1 because the scene is new. The high score survived the restart, and the scoreboard and the level's pickups did not.
Press F5 again to stop Play.
Next steps
- Data-driven design — tune game values in the Inspector instead of in code.
- Components — the lifecycle, attributes and references between components.
- Scenes — loading and switching scenes, and additive scenes.
- Input — rebindable controls and gamepads.