我是Zenject(扩展项目)的新人。
我的开发环境:Win10、Unity2020、扩展对象9.2.0
我的问题是:
- 在安装程序中绑定类**
第一个月
- 在A类注入**
private AccountInfo accountInfo;
[Inject]
private void Init(GameSetup _gameSetup, AccountInfo _accountInfo)
{
this.gameSetup = _gameSetup;
this.accountInfo = _accountInfo;
}
accountInfo.address = "xxx'; // works fine
- 然后将帐户信息注入到类B**
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
- 为什么accountInfo更改为null?AsCached()不起作用?还是其他问题?**
- 请帮帮我~~谢谢!**
下面是我的代码:
- 安装程序**
- 安装程序**
"ClassA"注入GameSetup并创建示例,工作正常*
"ClassB"注入游戏设置,错误:空对象*
"ClassB"创建者,我正在尝试使用container. instantiate()来创建它*
- --更新---游戏设置仍然为空对象
2条答案
按热度按时间gj3fmq9x1#
在两种情况下,注入将无法在代码中正常工作。
1.使用注入对象的代码在
Init
之前执行。例如,如果此代码放置在构造函数中。1.你可以在运行时创建你的游戏对象/组件而不使用
IInstantiator
。当你使用Znject时,你应该总是使用IInstantiator
来创建对象。要做到这一点,你应该将IInstantiator
注入到对象中,这会创建另一个对象。IItstantiator
在默认情况下总是绑定在容器中,所以你不必手动绑定它。例如:svmlkihl2#
我不是Maven,但我认为传递
IInstantiator
或容器不是一个好的做法。如果你需要在运行时创建注入示例,那么你需要一个工厂。1.-DI的最佳实践是只引用复合根“层”中的容器
请注意,工厂是该层的一部分,可以在那里引用容器(这对于在运行时创建对象是必需的)。
2.-直接示例化对象时,可以使用DiContainer或IInstantiator,DiContainer继承自IInstantiator。但是,请注意,注入DiContainer通常是不好的做法,因为几乎总是有更好的方法来设计代码,使您不需要直接引用DiContainer。
3.-同样,依赖项注入的最佳做法是仅引用“复合根层”中的DiContainer