Skip to content

Containers

Vladislav Kantaev edited this page Feb 10, 2022 · 9 revisions

Containers allow to setup global dependencies.

Root Dependency Container

RootDependencyContainer serves as an entry point to other containers. They should be attached to a RootDependencyContainer as children in order to work.
It is possible to have several RootDependencyContainer's. Together they form a stack: a RootDependencyContainer that was registered the latest, will have the highest priority when resolving global dependencies.

Container Types

  • Children Dependency Container: registers all active children.

  • List Dependency Container: registers all the objects specified via the Inspector. Given a GameObject is selected, it allows to specify the exact component on it.

  • Fallback Dependency Container: scans for all conforming objects on the active scenes. Since it relies on FindObjectsOfType(), it can only return objects deriving from UnityEngine.Object.

  • Defining custom containers: allows to register any dependencies from code. Very useful if the registered types do not derive from UnityEngine.Object.

public sealed class CompositionRoot : DependencyContainerBase
{
    protected override void ComposeDependencies(ContainerBuilder builder)
    {
        // Compose your dependencies here:
        builder.Register(new T());
        builder.Register<T>();
        builder.RegisterFromMethod((Dependency dep) => new MyObject(dep));

        // Can use fluent syntax:
        builder
            .Register<T1>()
            .Register<T2>()
            ;
    }
}

Note: There is an order in which containers are queried. That is, if a container was not able to resolve the dependency, the next one will be queried. The order of containers is the same as in the Inspector.