Public API Providing
Common
Injector
staticAccess to the provider list from code, and to the dependencies its providers supply. Call it on the Unity main thread.
| IReadOnlyList<Provider> Providers { get; } | Every provider in the list, in the order they are tried, disabled ones included. |
|---|
| void AddFirst(Provider provider) | Adds a provider at the front of the list, so it is tried before every other; the provider added most recently is tried first. Use it for a provider that must win, such as a test double. A provider added in Edit mode stays until it is removed, one added in Play mode is removed when you exit Play mode, and one added during a test is removed when the test ends. Throws ArgumentNullException when the provider is null. Throws ArgumentException when it is already added, when its class does not override exactly one of Provide and ProvideAsync, or when it overrides both TearDown and TearDownAsync. |
|---|---|
| void AddLast(Provider provider) | Adds a provider at the end of the list, so it is tried only after every other declined. It is removed under the same rules as one added with AddFirst. Throws the same exceptions as AddFirst. |
| void Remove(Provider provider) | Removes a provider added with AddFirst or AddLast. Does nothing for a provider that was not added. Throws ArgumentNullException when the provider is null. |
| LocalDependencies Local<T>(T dependency) LocalDependencies Local<T1, ..., T8>(T1 first, ..., T8 eighth) | Opens a local block that gives one to eight objects to everything created inside it, by new or Instantiate: using (Injector.Local(shot)) Instantiate(bulletPrefab);. What a block gives is tried before the provider list, and matches members like any other dependency. The Validation tab shows a member that a block with an object of that type could supply as May Be Supplied. Returns the open block; dispose it to end the block. Throws ArgumentNullException when one of the objects is null. |
| LocalDependencies Local(params object[] dependencies) | Opens a local block that gives any number of objects, as the typed overloads do. Throws ArgumentNullException when the array or one of the objects is null. |
Created, FirstInjected, LastReleased, TornDown. A handler that throws is logged, and the other handlers still run.| event Action<object, Provider> Created | Raised when a provider creates a dependency (Supply.Owned), before any member receives it. |
|---|---|
| event Action<object, Provider> FirstInjected | Raised when a dependency is injected into a member while no other member holds it. Raised for every dependency, created or borrowed. |
| event Action<object, Provider> LastReleased | Raised when the last member holding a dependency releases it. Raised for every dependency, created or borrowed. A created one is still intact and is torn down next; a borrowed UnityEngine.Object may already have been destroyed by its owner. |
| event Action<object, Provider> TornDown | Raised when Selvage ends an owned dependency, by destroying or disposing it. |
LocalDependencies
structAn open local block, returned by Injector.Local. Everything that runs inside the block gets its dependencies: code that awaits, coroutines started or yielding inside it, threads started inside it, and an object instantiated inside it while inactive, once it is turned on. A context keeps what it got after the block ends, and gets the same objects again when it is reinjected. An object lent from a Lifetime.Pooled pool inside the block also gets them, and so does one reinjected inside it with Manual.Reinject, such as an object reused from your own ObjectPool<T>; any other context that already existed does not. In nested blocks, the inner block's dependencies win. Selvage never destroys what you give a block.
| void Dispose() | Ends the block. A block that is never ended is logged as an error and ended at the end of the frame. |
|---|
Lifetime
enumWhether members share one object, each get their own, or borrow one from a pool, and when Selvage ends what it makes. To give each member its own, Selvage constructs your class, calls the function you added to a registry, copies a Unity object with Instantiate, or calls Clone() on an object that implements ICloneable.
| Permanent | Every member gets the same object, and one Selvage makes is kept while no member holds it: until play stops (one made in Edit mode, until scripts reload), or until its registry entry is removed. An object Selvage did not make, such as a scene object, behaves as with Shared. |
|---|---|
| Shared | Every member gets the same object. One Selvage makes ends once no member holds it. This is the default. |
| Separate | Each member gets its own object, made each time the member is injected or reinjected, and destroyed or disposed when the member releases it. |
| Pooled | Each member gets its own object, lent from a pool that grows as needed and given back to it when the member releases it. A lent object is injected again before the member gets it. A GameObject is turned off while it waits in the pool. Implement IResettable to reset an object between uses. |
IPreference
ifaceSettings that say which members get something when several things could be injected into them, such as which of two cameras the Hud gets. Each provider takes a preference in its own form: ProvideTuning on a scene object, PreferenceAttribute on a class, Preference for a registration, and ProvideDefinition for assets.
Set only the settings you need: a member matches when every setting set matches it. In a text setting, * stands for any text: "*Camera", "Enemy*". A member with only one possible dependency gets it whatever the preferences say, so a preference never takes a dependency away. When several preferences match, the one that says everything the others say and more wins: a derived ContextType or MemberAttribute, an inner Namespace or Under path, or a value another's pattern matches says more. When none wins, an error names them. A preference with no settings matches every member. Without a match, something with no preference is chosen before something whose preference doesn't match.
| Type ContextType { get; } | Matches members of a context of this type, or of a type deriving from it or implementing it. An open generic type such as typeof(Repository<>) stands for every type made from it. |
|---|---|
| Type AskedAs { get; } | Matches members that ask for exactly this type, such as IAudio for a class that is both an IAudio and an IMusic. An open generic type stands for every type made from it. |
| string MemberName { get; } | Matches members with this name. Case and a leading m_ or _ are ignored, in the name and in the setting alike, so no pattern tells _music from music. |
| Type MemberAttribute { get; } | Matches members that carry an attribute of this class, or of a class deriving from it, such as typeof(SerializeField) or one of your own. Only the attribute's class counts, not its arguments. |
| object Channel { get; } | Matches members whose channel is this value. |
| string Namespace { get; } | Matches contexts whose class is in this namespace, or in a namespace inside it. |
| string Assembly { get; } | Matches contexts whose class is in the assembly with this name. |
| string Tag { get; } | Matches contexts whose GameObject has this tag. |
| string Layer { get; } | Matches contexts whose GameObject is on this layer. |
| string Scene { get; } | Matches contexts whose GameObject is in the scene with this name. |
| string Under { get; } | Matches contexts whose GameObject is at this path from its scene's root, or below it: "UI/HUD". A / inside a GameObject's name counts as a level of the path. |
PromiseAttribute
attrsealedPromises that a provider has a dependency of a type whenever a member of that type is injected in Play mode, so the Editor counts those members as guaranteed: [assembly: Promise(typeof(IHttp))]. Use it for what your code adds at runtime, such as an object added to a registry before the first scene loads. When no provider has one, the member fails with an error naming the promise. Members injected in Edit mode are not covered. Explained in Require every member to be guaranteed.
| PromiseAttribute(Type dependency) | Promises that a provider has a dependency whenever a member of that type is injected in Play mode. A generic type definition, such as typeof(IRepository<>), covers every type made from it. |
|---|
| Type Dependency { get; } | The type of the members the promise covers. |
|---|---|
| float WithinSeconds { get; set; } | How long after a member is injected the dependency may arrive, in real time: zero (the default) means it is there at once. Above zero, members marked Async wait for it and fail once the time has passed without one, members marked Warm receive it once a provider has one, and the Editor reports the other members. float.PositiveInfinity waits without a limit. |
Scene
SceneProvider
sealedShipped provider that gives members the objects already in a loaded scene: a component, or any object of the requested type. A found object is shared and never destroyed by Selvage, unless a ProvideTuning on it sets another lifetime. When several objects could be injected into a member, a ProvideTuning preference on one of them decides first; otherwise the object closest to the context wins, and two objects equally close are an error that names both.
| Reach Reach { get; set; } | How far from the context the provider looks. |
|---|---|
| bool ParentsFirst { get; set; } | Whether parents are checked before children, when the reach includes the hierarchy. On by default. On each side, the closest object wins. |
| bool IncludeInactive { get; set; } | Whether objects that are turned off can be found. |
| bool RequireProvideTuning { get; set; } | Whether only objects whose GameObject has a ProvideTuning can be found, the context's own GameObject included. Off by default. A Provide Tuning covers every component on its GameObject. |
Reach
enumHow far SceneProvider looks from the context. Each step also covers the steps before it.
| Self | The context's own GameObject. |
|---|---|
| Hierarchy | Also its parents and children. |
| Scene | Also the rest of its scene. |
| AllScenes | Also every other loaded scene. A plain C# class is not on a GameObject or in a scene, so this is the only step that finds anything for it. |
ProvideTuning
MBsealedComponent that sets how SceneProvider provides the scene object it is on. Add it with Add Component > Selvage > Provide Tuning; a GameObject holds at most one. Without it, the object is shared and not watched, and a Scene provider set to RequireProvideTuning does not find it. With HasPreference on, it also says which members get this object when several objects could be injected into them. Implements IPreference, which lists its preference settings; the Channel setting is stored as text, and matches a member's channel written as text, such as the name of an enum value.
| Lifetime Lifetime { get; set; } | The object's lifetime, Shared by default. Permanent gives the same as Shared: Selvage never ends a scene object. Separate and Pooled give each member a copy of this object: its whole GameObject, duplicated beside it. |
|---|---|
| bool Watched { get; set; } | Whether members follow this object appearing and leaving, in Play mode. Off by default. When it is destroyed, every member holding it drops it on the next frame: a Reactive member receives a replacement when one exists, and any other member returns to its default. When it is enabled, Reactive members are injected again, and may move to it. When its GameObject is deactivated, WhenDeactivated applies. Turning this component off announces nothing. |
| WhenDeactivated WhenDeactivated { get; set; } | What a watched object does to the members holding it when its GameObject is deactivated. WhenDeactivated.Keep by default. |
| bool HasPreference { get; set; } | Whether the object has a preference. Off by default: the preference settings are then ignored, and hidden in the Inspector window. |
MemberAttribute to a class that is not an attribute class throws ArgumentException.WhenDeactivated
enumWhat a watched scene object does to the members holding it when its GameObject is deactivated, set on its ProvideTuning.
| Keep | Members keep it: a Reactive member is injected again from the whole provider list, and any other member keeps the object. |
|---|---|
| Revoke | Every member drops it on the next frame, as when the object is destroyed: a Reactive member receives a replacement when one exists, and any other member returns to its default. |
Attributes
AttributeProvider
sealedShipped provider that gives members an instance of each class marked [Provide], for every type the class is: the class itself, its base classes and its interfaces. What it gives is known before you enter Play mode, so the Editor can confirm these members will be injected. A class in a test assembly, an Editor assembly, or an assembly limited to some platforms replaces one from your main code while that assembly applies. The provider list holds at most one.
ProvideAttribute
attrsealedMarks a plain C# class to be provided by AttributeProvider: [Provide], or [Provide(Lifetime.Pooled)]. A shared instance is created the first time a member needs it, and ended once no member holds it, or once play stops or scripts reload with Lifetime.Permanent. A generic class is provided for every closed type it can become, as in [Provide] class Repository<T> : IRepository<T>; a non-generic class for the same type wins over it.
The class must not be abstract or static, and needs a constructor without parameters, which may be private. A Unity object (a component, a ScriptableObject, any asset) cannot be marked: put a component in a scene, and an asset in a folder with a ProvideDefinition. Code analysis reports a class that breaks these rules (SLV0007).
| ProvideAttribute(Lifetime lifetime = Lifetime.Shared) | Marks the class to be provided, with the lifetime of its instances. |
|---|
| Lifetime Lifetime { get; } | The lifetime of the class's instances. |
|---|
PreferenceAttribute
attrsealedSays which members get a class marked [Provide] when several classes could be injected into them: [Provide, Preference(ContextType = typeof(Hud))]. Several on one class give one instance for each. Implements IPreference, which lists its settings.
Registry
RegistryProvider
sealedShipped provider that gives members what your code adds to it. Reach the one in the provider list with RegistryProvider.Listed: RegistryProvider.Listed.Add<IAudio>(() => new Audio());, for example from a [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] method. What you add is given to members of its type, its base classes and its interfaces. Nothing you add is saved, and what you add in Play mode is removed when you exit Play mode. Its members are those of RegistryProvider<TSelf>.
RegistryProvider<TSelf>
abstractBase class of every registry. For a registry of your own, derive a class from it with itself as TSelf, mark it [Serializable], and add it to the provider list where it should be tried: [Serializable] public sealed class Cheats : RegistryProvider<Cheats> { }, then Cheats.Listed.Add<IDamage>(new GodMode());. The list holds at most one of each registry class. A registry created with new and added with Injector.AddFirst or Injector.AddLast is never Listed. Code analysis reports a class that passes another class as TSelf (SLV0005), and the provider list leaves it out.
| TSelf Listed { get; } | The TSelf in the provider list, enabled or not. It stays the same object until scripts are reloaded. In a build, the provider list loads before the first scene, so read it from RuntimeInitializeLoadType.BeforeSceneLoad on. Throws InvalidOperationException when the provider list has no TSelf or, in a build, when read before the list has loaded. |
|---|
| void Add<T>(T dependency, Lifetime lifetime = Lifetime.Shared, Preference preference = null, bool canRevoke = false) | Adds an object you already have, given to members of T and of every base class and interface of T. A Unity object destroyed later is removed, with a warning. Shared or Permanent, the object is never destroyed for you; Separate or Pooled, members get copies of it: a Unity object is copied with Instantiate, a plain object with its Clone(), so it must implement ICloneable. canRevoke lets a removal with revoked: true revoke what this entry gave, from every member holding it; each injection of it into a member that is not Reactive then costs a little more. Throws ArgumentNullException when the dependency is null, and ArgumentException when the lifetime asks for copies of an object that cannot be copied. |
|---|---|
| void Add<T>(Func<T> create, Lifetime lifetime = Lifetime.Shared, Preference preference = null, bool canRevoke = false) | Adds what create makes, given to members of T and of every base class and interface of T. create is called once for a shared object, or for each member that needs its own. Selvage ends what it makes once no member holds it (a Permanent one once play stops or scripts reload, or once the entry is removed), so return a new object, never one that exists elsewhere. Returning null declines, and the next provider is tried. canRevoke is as for the other overload. Throws ArgumentNullException when create is null. |
| bool Remove(object dependency, bool revoked = false) | Removes what was added with dependency, the same object, and ends the objects waiting in its pool. A Reactive member holding what it gave is injected again from the whole provider list, and any other member keeps it. With revoked, for an entry added with canRevoke: true, every member holding what it gave drops it on the next frame: a Reactive one receives a replacement when one exists, and any other returns to its default. For an entry added without it, Selvage logs a warning and doesn't revoke: members are reached as after any removal. Returns whether anything was removed. Throws ArgumentNullException when the dependency is null. |
| bool Remove<T>(Func<T> create, bool revoked = false) | Removes what was added with create: the same method, or the delegate passed to Add. A function written inline in the Add call cannot be passed again, so only Clear removes it. Otherwise as Remove(dependency). Throws ArgumentNullException when create is null. |
| void Clear(bool revoked = false) | Removes everything added to this registry, as Remove does for each entry. |
Preference
sealedSays which members get what you add to a registry when several things could be injected into them. Pass one to RegistryProvider.Add: registry.Add(hudCamera, preference: new Preference { ContextType = typeof(Hud) });. Implements IPreference, which lists its settings. Setting MemberAttribute to a class that is not an attribute class throws ArgumentException.
Assets
AssetProvider
sealedShipped provider that gives members the assets the project's ProvideDefinitions provide. A ScriptableObject, a material or any other asset is given as itself, so changes made to it in Play mode stay; turn on a definition's RuntimeCopy to share a copy instead. A prefab is instantiated, and members get that instance, or the component they ask for on it. What it gives is known before you enter Play mode, so the Editor can confirm these members will be injected.
An asset in a Resources folder loads the first time a member needs it. An addressable asset does too, for the members that can wait for it. Any other asset loads when the game starts. The provider list holds at most one.
ProvideDefinition
sealedAsset that provides its folder's assets, or the assets in its list, through the AssetProvider. Create one in a folder with Assets > Create > Selvage > Provide Definition. Its settings apply to every asset it provides. When two definitions could provide the same asset, the closer one provides it: a definition with the asset in its list, then the one in the deepest folder. Its settings are set in the Inspector. Implements IPreference, which lists its preference settings; the Channel setting is stored as text, and matches a member's channel written as text, such as the name of an enum value.
| AssetSelection Provides { get; } | Which assets the definition provides. AssetSelection.Folder by default. |
|---|---|
| IReadOnlyList<Object> Assets { get; } | The assets the definition provides when Provides is AssetSelection.List. |
| Lifetime Lifetime { get; } | The lifetime of the provided assets, Shared by default: the asset itself, or one instance of a prefab. Permanent keeps that instance until play stops (one made in Edit mode, until scripts reload). Separate and Pooled give each member its own instance of a prefab, or its own runtime copy of any other asset, never saved into the asset. |
| bool RuntimeCopy { get; } | Whether, with the Shared or Permanent lifetime, every member gets one copy of an asset instead of the asset itself, so changes made in Play mode never reach the asset. Off by default. A prefab is always given as an instance. |
| bool HasPreference { get; } | Whether the provided assets have a preference. Off by default: the preference settings are then ignored, and hidden in the Inspector window. |
AssetSelection
enumWhich assets a ProvideDefinition provides.
| Folder | Every asset in the folder that holds the definition. This is the default. |
|---|---|
| FolderAndSubfolders | Every asset in the folder that holds the definition, and in the folders inside it. |
| List | The assets in the definition's Assets list, wherever they are. |
Other
IResettable
ifaceInterface for a Lifetime.Pooled object that resets itself between uses. Implementing it is optional: a pooled GameObject is also turned off when given back and on when lent, so its OnDisable and OnEnable run.
| bool TryReset() | Called when the member holding the object releases it, before the object goes back in the pool; its dependencies are still there. Put the object back in the state it had when first made, and return true. Return false when it cannot be reset: it is then destroyed or disposed instead of reused. |
|---|