ssannandeji / Zenject-2019

Dependency Injection Framework for Unity3D
MIT License
2.53k stars 363 forks source link

Null is getting injected into factories #589

Closed Rhast0r closed 5 years ago

Rhast0r commented 5 years ago

Here is an example of how to reproduce the error. It does not only happen with the SignalBus but with any other binding made

public class ExampleInstaller : MonoInstaller
{
    public override void InstallBindings()
    {
        Container.DeclareSignal<ExampleSignalSignal>();
        SignalBusInstaller.Install(Container);
        Container.BindFactory<ExampleMonobehaviour, ExampleMonobehaviour.Factory>().FromNewComponentOnNewGameObject().AsSingle().NonLazy();
    }
}

public class ExampleMonobehaviour : MonoBehaviour
{
    public class Factory : PlaceholderFactory<ExampleMonobehaviour>
    {
        private SignalBus _signalBus;

        [Zenject.Inject]
        private void Construct(SignalBus signalBus)
        {
            if (signalBus == null)
                throw new ArgumentNullException(nameof(signalBus));

            _signalBus = signalBus;
        }

        public override ExampleMonobehaviour Create()
        {
            var exampleMonobehaviour = base.Create();
            _signalBus.TryFire(new ExampleSignalSignal(exampleMonobehaviour));
            return exampleMonobehaviour;
        }
    }
}

public class ExampleSignalSignal
{
    public ExampleMonobehaviour ExampleMonobehaviour { get; }

    public ExampleSignalSignal(ExampleMonobehaviour someMonobehaviour)
    {
        this.ExampleMonobehaviour = someMonobehaviour;
    }
}
svermeulen commented 5 years ago

I assume you mean that it only happens during validation? When I run that code and call Create() on your factory it works fine.

During validation, zenject only instantiates those classes that implement the IValidatable interface, which PlaceholderFactory does. This is why it tries to create your factory during validation. But SignalBus is not an IValidatable so it gets injected as null.

Can you just remove your null checking in the constructor of your factory? Since null is expected there during validation so not really an error

svermeulen commented 5 years ago

By the way - see here for more details: https://github.com/svermeulen/Zenject#object-graph-validation