Overview

Selvage takes dependencies from where they already are in your project: your scenes, your asset folders, your classes, and any source you write a provider for. Most dependency injection frameworks are containers instead: before a script can receive an object, code registers that object, or a way to create it, in the container.

Selvage is built for Unity rather than adapted from a .NET container, so it also follows Unity's own rules: when objects are created, how long they live, and what the Editor can check before you enter Play mode.

Provide from any source

A provider gives dependencies from one source, and the provider list orders the providers of your project. Each kind of object comes from the source that already holds it, with little or no code:

What you provideWith a containerWith Selvage
A component in a sceneA binding that searches the hierarchy.Nothing to write: the Scene Provider gives the closest one. For more information, refer to Provide scene components.
A ScriptableObject or a prefabA reference assigned to an installer.A Provide Definition in its folder. For more information, refer to Provide assets.
One of your classesA binding in an installer.[Provide] on the class. For more information, refer to Provide your own classes.
An object your code createsAn instance registered in the container.RegistryProvider.Listed.Add(obj), or a local block. For more information, refer to Provide objects your code creates.
Data from a file, a server or a platform serviceA factory method for each binding.A provider of your own.

A provider of your own is a class with two methods. Evaluate states which types the provider can give, without running anything, and Provide gives the dependency for one member, with its context and channel at hand:

[Serializable]
public sealed class MainCameraProvider : Provider
{
    protected override Verdict Evaluate(Request request)
        => (request.Type == typeof(Camera)) ? Verdict.Maybe() : Verdict.Never;

    protected override Supply Provide(Request request, object context, object channel)
        => (Camera.main != null) ? Supply.Borrowed(Camera.main) : Supply.Decline();
}

Your provider gets the same treatment as the providers that ship with Selvage: the Dependencies window validates the members it serves, Selvage ends what it owns once no member holds it, and it can load in the background or announce a newer dependency. For more information, refer to Write a custom provider.

The order of the provider list is the priority. To change where a dependency comes from, move a provider in the list, or add one before the list from code. No script changes. For more information, refer to Manage the provider list.

Inject without wiring code

A member only declares what the script needs. Nothing registers the script, and nothing calls a resolve method: Selvage injects each context when it's created: at the end of Awake for a MonoBehaviour, or of the constructor for a plain C# class. Selvage adds that call when Unity compiles your scripts.

As a result, new and Instantiate inject what they create, so a prefab needs no factory, and the static members of a class are injected too. To pass data to the objects you create, such as the direction of a bullet, use a local block. It also reaches the coroutines and await continuations started inside it:

using (Injector.Local(new BulletShot(direction)))
    Instantiate(bulletPrefab);   // its [Inject] BulletShot member receives this direction

For more information, refer to Injection lifecycle.

Inject without marking members

A scope injects every field and property of a class, an assembly or the project, so its members don't need [Inject]. The project scope is the Inject by Default setting: it injects the scripts of every assembly that references Selvage, Assembly-CSharp included, even scripts that never mention Selvage:

public class Player : MonoBehaviour
{
    Rigidbody body;   // injected while Inject by Default is enabled
}

Options can be set on a scope too, such as EditMode for a whole assembly. For more information, refer to Inject with scopes.

Choose with what your code already says

When several objects could be injected into a member, a preference on each candidate says which members it's for, from facts your code already holds: the member's name, an attribute on the member, the class, namespace or assembly of the context, and the tag, layer, scene or hierarchy path of its GameObject. A container needs a key written on both sides instead.

[Provide, Preference(MemberName = "music")]
public class MusicBus : IAudioBus { ... }

[Provide, Preference]                     // for every other member
public class EffectsBus : IAudioBus { ... }

[Inject] IAudioBus music;      // MusicBus, also for m_music and _music
[Inject] IAudioBus footsteps;  // EffectsBus

A preference is a hint, never a filter: a member with one candidate receives it, whatever the preference, so a script copied into another project keeps working there. When nothing in your code tells the candidates apart, a channel on the member names the one it wants, and [DynamicChannel] reads that channel from a field of the context each time the member is injected. For more information, refer to Choose between several candidates.

Asynchronous dependencies

Waiting for a dependency that takes time, such as an Addressables asset, is part of injection. An Async member keeps its default until its dependency arrives, and its context is ready once every member is injected. You wait in the form your code already uses:

yield return Context.WhenReady(this);                    // a coroutine
await Context.WhenReady(this);                           // an async method
Context.WhenReady(this).Completed += operation => ...;   // an event handler
if (Context.IsReady(this) == false) return;           // code that runs every frame

A provider loads in the background with ProvideAsync. Members that share one instance wait for a single load, Selvage cancels the load once no member waits for it, and a result that completes anyway is ended, so nothing leaks. The Asset Provider loads Addressables assets this way. Contexts whose Async members wait for each other in a loop become ready together, and the Dependencies window shows which members need the option. For more information, refer to Async and Asynchronous providers.

Dependencies that change

A container injects a dependency once. With Selvage, a provider announces a newer dependency with RaiseChanged, or revokes one that must no longer be used. The registry announces every object you add or remove, and a scene object with Watched enabled announces when it appears and when it's destroyed. A Reactive member receives each new dependency, and its set accessor runs with each one. It also receives a dependency from a provider added above the one that gave it.

A Warm member receives the best dependency that's ready now, while the ones that take time are prepared in the background. It receives a prepared one as soon as it's ready when it's also Reactive, or on the next Manual.Reinject. For more information, refer to Reactive and Warm.

Lifetimes that follow Unity objects

A container makes you declare container scopes, such as one per scene or per prefab, and bind objects in each. Selvage has none to declare: what members share per scene, per prefab instance or per spawned object follows from where objects are and which members hold them. For the equivalent of each container scope, refer to Container scopes.

An object Selvage creates lives while a member holds it. Selvage ends only what it created: it destroys a Unity object and disposes an IDisposable, and never ends an original scene component or asset, or an object you added yourself. Lifetimes apply to every source:

  • A Shared object ends one frame after no member holds it, so a member of a newly loaded scene can still take it over, where a container singleton lives as long as its container. A Permanent object stays until play stops (one made in Edit mode, until scripts reload).
  • A scene object with the Separate or Pooled lifetime gives each member its own copy of its GameObject, set with a Provide Tuning component.
  • A ScriptableObject with Separate or Pooled gives each member a copy that's never saved into the asset, and Runtime Copy gives every member one shared copy, so Play mode changes never reach the asset.
  • A pool grows as needed, turns a GameObject off while it waits, and resets an object that implements IResettable.
  • A Weak member doesn't keep its dependency alive, so two objects that hold each other can still end.

For more information, refer to Lifetimes.

Swap dependencies by assembly

A class marked [Provide] in a test, Editor or platform assembly replaces the classes of your other assemblies wherever that assembly applies. You place the class in the right assembly, with no #if and no rebinding:

// In an Editor assembly: IStore members receive MockStore in the Editor, and SteamStore in a build.
[Provide]
public class MockStore : IStore { ... }

A provider added from code during a Test Runner test is removed when the test ends. For more information, refer to Swap dependencies for tests and platforms.

Check and inject in the Editor

The Inspector window and the Validation tab of the Dependencies window tell you whether each member will receive a dependency, before you enter Play mode and without running your code. Each member is Guaranteed, May Be Supplied or Missing, and Explain shows which provider gives it and why each provider above didn't. By default, a build with a Missing member is blocked. With strict validation, a project passes only when every required member is Guaranteed, and [assembly: Promise] counts a type your code provides at runtime. Code analysis reports mistakes in your IDE as you type. For more information, refer to Validate members.

Injection also works outside Play mode: an EditMode member is injected in Edit mode, for [ExecuteAlways] scripts, ScriptableObjects and Editor tools. The Live tab of the Dependencies window shows what each member holds, in Edit mode and in Play mode. For more information, refer to EditMode and Inspect injected members.

IL2CPP, domain reload and performance

Selvage assigns members with code that an IL post-processor adds when Unity compiles your scripts, not with reflection, so IL2CPP builds need no link.xml entry for your scripts. It supports Enter Play Mode with domain reload disabled, and starts no threads, so WebGL needs no special handling. A synchronous injection allocates nothing per member, and injects an object with one member in about 2 µs in an IL2CPP release build. For more information, refer to Technical Q&A.