Create a provider

A provider is a class that derives from Provider, in the Selvage.Extensions namespace. It answers a member's request in two steps:

  1. Evaluate returns a verdict: whether the provider can give the requested type.
  2. Provide returns the dependency, when the verdict allows it.

The following provider gives the main camera:

using System;
using Selvage.Extensions;
using UnityEngine;

[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();
}

To use the provider, add it to the provider list with +. The class must have the [Serializable] attribute and a constructor without parameters. Without [Serializable], the + menu shows the class disabled, with the reason.

The Request holds what Selvage knows about the member before it's injected:

PropertyDescription
TypeThe type asked for: the member's type, or the type a verdict redirects to (refer to Verdicts).
ContextTypeThe type of the context.
MemberThe field or property, such as to read an attribute on it. null when no member is behind the request.
ElementTypeThe element type when Type is an array or an IEnumerable<T>, otherwise null.
FixedChannelThe member's [Channel], when it has no [DynamicChannel], otherwise null.

The channel argument of Provide, and of every other method below that takes one, holds the member's channel at injection: the value of its [DynamicChannel], else its [Channel], else null. A channel is a hint, so a provider can ignore it. A verdict that reads FixedChannel lets the Validation tab settle a choice by channel before you enter Play mode.

Selvage calls Evaluate once per member, and in Edit mode too: the Validation tab of the Dependencies window displays its verdict. Evaluate must therefore only read the Request and the provider's own settings, and never the scene, a static field or the time. Selvage calls Provide at each injection, with the context and the member's channel, so this is where you look up or create the dependency. For a static member, the context is the class's Type. Selvage calls every method of a provider on the main thread.

Verdicts

VerdictDescriptionValidation result
Verdict.NeverThe provider never gives this type. Selvage tries the next provider.The next provider's result
Verdict.Maybe()Provide can decline, because whether it has a dependency is only known when the member is injected.May Be Supplied
Verdict.Always()Provide always gives a dependency. A decline after this verdict is an error.Guaranteed
Verdict.Veto(reason)No provider gives this type: Selvage tries no provider below. Use it to forbid what a provider below would give. The Validation tab shows reason, and so does the error a required member fails with.Missing
Verdict.Redirect(type)Give what the provider list gives for another type, such as a class for its interface. The type must be assignable to the requested type, otherwise Selvage logs an error and the dependency is missing.That type's result

Maybe and Always take three optional arguments:

  • canRevoke, for a dependency that may have to be dropped while members hold it. For more information, refer to Dependencies that change.
  • mustWait, for a dependency that takes time. For more information, refer to Asynchronous providers.
  • makes, the class the provider creates for the request, when you know it before you enter Play mode. The Validation tab then follows that class's members to report a dependency cycle that never ends. A provider that doesn't override ShareKey creates a new instance for each member; one that does is taken to share what it creates, which closes a cycle.

Supplies

Provide returns a Supply, which holds the dependency and indicates whether Selvage ends it:

SupplyDescription
Supply.Borrowed(instance)An object that belongs to something else, such as a component or an asset. Selvage never injects or ends it.
Supply.Made(instance)An object the provider has just made, or taken from its own pool. Selvage injects it, and the provider ends it in TearDown.
Supply.Owned(instance)An object Selvage injects, and ends once no member holds it.
Supply.Decline(reason)No dependency. Selvage tries the next provider. After Verdict.Always, the error Selvage logs gives reason.
Supply.Veto(reason)No dependency, and no provider below may give one: the member is missing, and Selvage logs reason as an error. Use it when what decides is only known at injection, such as several candidates nothing tells apart.

If Evaluate, ShareKey or Provide throws an exception, the member fails, Selvage logs the exception with the provider's name, and tries no other provider. Supply.Borrowed, Supply.Made and Supply.Owned throw an exception when you pass null or a destroyed Unity object: to give nothing, return Supply.Decline().

When the last member releases an instance, two steps run in order:

  1. The provider's TearDown(instance), or TearDownAsync(instance), for every instance it gave, borrowed, made or owned. It does nothing by default. Override it to run your own code, such as returning the instance to your own pool.
  2. For an owned instance only, Selvage ends it: it destroys a Unity object (with DestroyImmediate in Edit mode), and disposes an object that implements IDisposable or IAsyncDisposable.

A provider that ends an instance its own way gives it with Supply.Made, and ends it in TearDown. Selvage waits for TearDownAsync to complete before it tears down the next member's dependency, and logs a teardown that fails with the provider's name.

Share an instance

To give one instance to several members, override ShareKey. Requests that return the same key share one instance, and Selvage doesn't call Provide again for them:

protected override object ShareKey(Request request, object context, object channel)
    => typeof(ISaveSystem);   // one instance for every member

The key defines what "the same instance" means. For example, return request.ContextType for one instance per class, the context's GameObject for one instance per GameObject, or the channel for one instance per channel. Selvage calls ShareKey for every request, so the same context must always return the same key.

While an instance is being created, such as by ProvideAsync, every request for its key waits for that one creation. Once no member holds a shared owned instance, Selvage ends it at the end of the next frame, so a member injected in between, such as after a scene load, receives the same instance. A shared borrowed instance that its owner destroys is looked up again.

Asynchronous providers

To load or fetch a dependency, override ProvideAsync instead of Provide:

protected override Verdict Evaluate(Request request)
    => (request.Type == typeof(Catalog)) ? Verdict.Maybe(mustWait: true) : Verdict.Never;

protected override async ValueTask<Supply> ProvideAsync(
    Request request, object context, object channel, CancellationToken cancellationToken)
{
    Catalog catalog = await Catalog.LoadAsync(cancellationToken);
    return (catalog != null) ? Supply.Owned(catalog) : Supply.Decline();
}

With mustWait: true, only Async and Warm members use the provider. A member that can't wait receives from such a provider only a shared instance that already exists, and the Validation tab flags a member that only such providers serve. A result that's ready at once completes without waiting a frame.

Selvage cancels the token once no member waits for the result, or when you exit Play mode. A result that completes anyway is torn down as described in Supplies, so ignoring the token never leaks an instance. Detach on the member's side never cancels the token.

A provider overrides exactly one of Provide and ProvideAsync, and at most one of TearDown and TearDownAsync. Code analysis reports other combinations as SLV0004.

Dependencies that change

When what the provider gives changes, call one of the following methods. Selvage applies the changes on the next frame, every change of a frame together.

MethodCall it whenMembers
RaiseChanged()What the provider gives may have changed: a newer version of what it supplied exists, or it can give something it couldn't before.Every Reactive member holding what it supplied is injected again from the whole provider list, and so is every Reactive member holding nothing. Other members keep what they hold.
RaiseChanged(dependency)One dependency it supplied has a newer version.Only the Reactive members holding that dependency are injected again.
RaiseChanged(revoked: true), RaiseChanged(dependency, revoked: true)What it supplied must not be used any more, such as a closed connection.Every Reactive member holding it drops it, and receives a replacement when one exists. A member that isn't Reactive drops it too, and returns to its default, when it was supplied with canRevoke: true.
Reevaluate()Something Evaluate reads has changed, such as a setting.Selvage forgets the verdicts it remembered from this provider and asks again, then reaches the members as RaiseChanged() does.

Telling a member that isn't Reactive about a revoke costs a little at each injection, so it's opt-in. Pass canRevoke: true in one of the following places:

  • The verdict, Verdict.Maybe(canRevoke: true) or Verdict.Always(canRevoke: true): every dependency of the request can be revoked. The Validation tab indicates it on the member's row.
  • The supply, Supply.Borrowed(instance, canRevoke: true), and the same argument of Supply.Made and Supply.Owned: only that object can be revoked, such as one that your provider knows can go away.

RaiseChanged(dependency) returns whether members hold the dependency from this provider, and reaches no member otherwise. A revoke that reaches no member logs a warning. Call these methods on the main thread.

Provider settings

A provider's serialized fields are its settings in the provider list, and Unity draws them as in any Inspector window. Editing them in the provider list, and changing Enabled, call Reevaluate() for you. When your own code changes a setting that Evaluate reads, call Reevaluate().

When you rename a provider class, add the [MovedFrom] attribute so the provider list still finds it.

To allow only one instance of your provider in the list, add the [OnePerList] attribute. Each derived class counts on its own, and providers added from code aren't limited. To reach the listed instance from code, give your class a property that calls InList<T>(), which returns the first T in the list, enabled or not, or null:

[Serializable, OnePerList]
public sealed class MainCameraProvider : Provider
{
    public static MainCameraProvider Listed => InList<MainCameraProvider>();
    ...
}

Ship a provider in a package

A provider class in a package appears in the + menu of the provider list in every project that imports the package. To add the provider without user action, add it from code:

[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
static void Register() => Injector.AddLast(new MyProvider());