我是依赖注入的新手,我已经进行了几天的研究,但似乎找不到答案; zenject并没有很多例子,所以我一直在研究具体的zenject解决方案以及一般的DI。
使用Unity 2018.3f和Zenject 7.3.1。
我正在使用接口IModifiableService以便构造函数将我的ModifiableService类注入到我的ModifiableField类中,以填充其依赖关系。
在控制台登录构造函数期间,它正按预期方式注销“ ModifiableService”。当再次用于从ModifiableField脚本调用以触发Calculate()的单独方法中时,控制台日志为null。我似乎丢失了一些东西或做错了此事,因此,我将不胜感激任何资源或建议,以便更好地理解DI以及如何解决我的问题。谢谢!
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);
}
}
绑定:
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."));
}
}
试图将其更改为以不同的方式在安装程序中执行相同的操作;达到了相同的结果,使我认为我的安装程序是问题所在,而以上两种尝试均未正确绑定它。