I'm new to Dependency Injection and I have been doing my research for a few days now but can't seem to find answers; there is not a whole lot of examples out there specific to zenject so I have been looking into both specific zenject solutions as well as DI in general.
Using Unity 2018.3f and Zenject 7.3.1.
I'm using an interface IModifiableService in order to constructor inject my ModifiableService class into my ModifiableField class in order to fill it's dependency.
During the console log in the constructor it is logging out "ModifiableService" as expected. When used again in a separate method which is called from the ModifiableField script to trigger Calculate() the console log is null. I seem to be missing something or doing this incorrectly so I would greatly appreciate any resources or advice in order to better understand DI and how to fix my issue. Thanks!
public class ModifiableField
{
[SerializeField] private ModifiableProperty propertyToModify;
[SerializeField] private float modificationAmount;
[SerializeField] private IModifiableService _modifiableService;
ModifiableField(IModifiableService modifiableService)
{
_modifiableService = modifiableService;
//Not Null
Debug.Log(_modifiableService);
}
public IModifiableService ModifiableService { get => _modifiableService; private set => _modifiableService = value; }
public ModifiableProperty PropertyToModify { get => propertyToModify; private set => propertyToModify = value; }
public float ModificationAmount { get => modificationAmount; private set => modificationAmount = value; }
public void Calculate()
{
//Null
Debug.Log(_modifiableService);
ModifiableService.TriggerAttributeChange(PropertyToModify);
}
}
Binding:
public class MISInstaller : MonoInstaller
{
public override void InstallBindings()
{
SignalBusInstaller.Install(Container);
//Both of these lines to bind IModifiableService produce the same null result.
//Container.BindInterfacesAndSelfTo<ModifiableService>().AsCached().NonLazy();
//Container.Bind<IModifiableService>().To<ModifiableService>().AsCached().NonLazy();
Container.Bind<ModifiableField>().AsTransient().NonLazy();
Container.DeclareSignal<ModAgilitySignal>();
Container.DeclareSignal<ModStrengthSignal>();
Container.BindInterfacesAndSelfTo<ModAgilitySignal>().AsCached().NonLazy();
Container.BindInterfacesAndSelfTo<ModStrengthSignal>().AsCached().NonLazy();
Container.BindSignal<ModAgilitySignal>().ToMethod(() => Debug.Log("Agility Modifiable Signal Fired."));
Container.BindSignal<ModStrengthSignal>().ToMethod(() => Debug.Log("Strength Modifiable Signal Fired."));
}
}
Tried changing it to do the same thing a different way in the installer; same result was achieved, making me think my installer is the problem and it was not being bound correctly in either of my above attempts.