Inject Classes

Use Zenject Dependency Injection

There are different ways to inject classes using dependency injection. Zenject provides constructor, field, property, and method injection.

It is recommended to only use Constructor and Method Injection. Read more here

Constructor Injection

Most of your scripts will probably inherit form MonoBehaviour so you will not be able to use constructor injection. If your class is a service or helper class that does not inherit MonoBehaviour then you can use constructor injection.

internal class DependencyInjectionExample
{
    private EasyEvents _events;

    public DependencyInjectionExample(EasyEvents events)
    {
        _events = events;
    }
}

Zenject dependency Injection will automatically provide an instance of EasyEvents into the DependencyInjectionExample class

Zenject will inject dependencies during Unity'sAwake() phase. Recommended to access the injected dependencies in the Start()method instead of Awake()

Method Injection

Most of your scripts will probably inherit form MonoBehaviour so you will not be able to use constructor injection. In that case you will need to use Method injection. There 2 ways that you can use Method Injection.

1. Have a private variable that is assigned via method injection and used throughout your class. Injected only once.

I have named the method Initialize() but you can use whatever method name you want. I have seen other people use the naming convention Constructor() since it acts like a constructor for classes that inherit from MonoBehaviour

internal class DependencyInjectionExample : MonoBehaviour
{
    private EasyEvents _events;

    [Inject]
    private void Initialize(EasyEvents events)
    {
        _events = events;
    }
    
    public void AddEvent()
    {
        _events.LoggedIn += OnLoggedIn;
    }

    public void RemoveEvent()
    {
        _events.LoggedIn -= OnLoggedIn;
    }

    private void OnLoggedIn(ILoginSession loginSession)
    {
        Debug.Log($"User {loginSession.LoginSessionId.DisplayName} has logged in");
    }
}

2. Inject the class into every method that needs. Injected into every class with [Inject] attribute

internal class DependencyInjectionExample : MonoBehaviour
{
    [Inject]
    public void AddEvent(EasyEvents events)
    {
        events.LoggedIn += OnLoggedIn;
    }

    [Inject]
    public void RemoveEvent(EasyEvents events)
    {
        events.LoggedIn -= OnLoggedIn;
    }

    private void OnLoggedIn(ILoginSession loginSession)
    {
        Debug.Log($"User {loginSession.LoginSessionId.DisplayName} has logged in");
    }
    
    [Inject]
    private void AudioSettings(EasyAudio audio)
    {
        audio.AdjustLocalPlayerAudioVolume(25, EasySession.Client);
    }
}

Last updated