Injecter

Inject is the process of getting the binded objects from the container. There are various ways to assign dependencies of an object. The dependencies of objects derived from MonoBehaviour are given in the Definitions, the dependencies of objects that do not derive from MonoBehaviour are given in the Constructor. In order to assign injections to these objects, the Inject attribute must first be used. It is not necessary to use it in the constructor, it just increases the injection priority. InjectAttribute = Inject attribute can be applied to Field, Property, Method, Constructor and Parameter. This attribute also keeps the id received while binding and ensures that it is injected according to the relevant id.

Sample uses:

public class SampleClass : MonoInjecter
{
    [Inject]
    private readonly SignalController _signalController;

    [Inject("foo1")]
    private readonly Foo _foo;
}
public class SampleClass
{
    private readonly Foo _foo;

    public SampleClass([Inject("foo1")] Foo foo)
    {
        _foo = foo;
    }
}

If a class has more than one constructor, whichever constructor has the inject attribute is called.

public class SampleClass
{
    private readonly Foo _foo;

    public SampleClass(Foo foo) //Not called
    {
        _foo = foo;
    }

    [Inject]
    public SampleClass() //Called
    {
    }
}

If the inject attribute is not used at all, the one with the largest number of parameters is called.

public class SampleClass
{
    private readonly Foo _foo;

    public SampleClass(Foo foo) //Called
    {
        _foo = foo;
    }

    public SampleClass() //Not called
    {
    }
}

There are 3 different injection methods

  • MonoInjecter = If there is a MonoBehaviour object that is not created with Factory, the fastest way to give dependencies is to derive this class from MonoInjecter. With this class, dependencies are injected from the SceneContext in Awake method.

  • SceneInjecter = If there is a MonoBehaviour object that is not created with Factory and does not derive from MonoInjecter, another way to give dependencies is to have a SceneInjecter in the scene. This class finds all MonoBehaviors in the entire scene in Awake and injects their dependencies one by one from the relevant SceneContext. It can be created in the scene by selecting Tarject/SceneInjecter from the MenuItems. It is recommended to inherit each scene object to be injected from MonoInjecter for faster injecting.

  • Factory = Another way to give the dependencies of objects is to create the relevant object with Factory. During creation, dependencies are injected from the container of the context to which the Factory is binded. This method can be used for all objects.

Last updated