[SOLVED] Extenject – NullReferenceException when second time inject

Issue

This Content is from Stack Overflow. Question asked by Stormer

Here is my question:

In installer bind the class

Container.Bind<AccountInfo>().AsCached();

Inject it at classA

private AccountInfo accountInfo;             

[Inject]
private void Init(GameSetup _gameSetup, AccountInfo _accountInfo)
{
    this.gameSetup = _gameSetup; 
    this.accountInfo = _accountInfo;
}

accountInfo.address = "xxx'; // works fine

Then inject AccountInfo to classB

private AccountInfo accountInfo;      
        
[Inject]
private void Init(AccountInfo _accountInfo)
{
    this.accountInfo = _accountInfo;
}

accountInfo.address = "xxx'; //NullReferenceException: Object reference not set to an instance of an object

Why accountInfo changed to null? AsCached() dosen’t work? Or something worng else?

Help please~~ Thank you!



Solution

There are two cases, when injection will not work properly in your code.

  1. The code, that uses injected object is executed before Init. For example if this code is placed in the construcor.

  2. You create your GameObject/Component in runtime whithout using IInstantiator. While you use Znject you always should use IInstantiator to create objects. To do it you should inject IInstantiator to the object, that creates another objects. IItstantiator is always binded in the container by default, so you don’t have to bind in manually. For example:


public class Creator : MonoBehaviour {

    [SerializeField]
    private GameObject _somePrefab;

    private IInstantiator _instantiator;

    [Inject]
    public void Initialize(IInstantiator instantiator) {
        _instantiator = instantiator;
    }

    private void Start() {

        // example of creating components
        var gameObj = new GameObject(); // new empty gameobjects can be created without IInstantiator
        _instantiator.InstantiateComponent<YourComponentClass>(gameObj);

        // example of instantiating prefab
        var prefabInstance = _instantiator.InstantiatePrefab(_somePrefab);
    }

}


This Question was asked in StackOverflow by Stormer and Answered by Nikolai It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?