简体   繁体   English

牙签绑定彼此依赖的模块

[英]Toothpick bind modules that depends on each other

I am trying out the toothpick DI library and I seem to miss something crucial. 我正在尝试牙签DI库,我似乎错过了一些至关重要的东西。

I created the following test project on github where I tried to make a smallest possible use case for my understanding issue. 在github上创建了以下测试项目,在那里我尝试为我的理解问题制作一个尽可能小的用例。

There you will find the ApplicationModule where I try to inject everything I need in my "root" module. 你会在那里找到ApplicationModule ,我尝试在“root”模块中注入我需要的所有内容。 As you can see there, I have twice scope.installModules(module) because my PlainPojo depends on the Application instance. 正如你在那里看到的,我有两次scope.installModules(module)因为我的PlainPojo依赖于Application实例。 If I do not do the first installModule call, I have no application instance in the scope. 如果我没有进行第一次installModule调用,我在范围内没有应用程序实例。 I could, as mentioned in the comment, pass the application instance as a parameter but I thought that I can remove them when I use DI? 我可以,如评论中所提到的,将应用程序实例作为参数传递,但我认为我可以在使用DI时将其删除?

The second class that causes troubles is the SimpleTest class. 导致麻烦的第二个类是SimpleTest类。 If I do not call the inject() method in the constructor, the PlainPojo member will not be injected. 如果我不在构造函数中调用inject()方法,则不会注入PlainPojo成员。 I also tried to use a third time the installModules() in the ApplicationModule after binding the PlainPojo but that does not help. 在绑定PlainPojo之后,我还尝试在ApplicationModule第三次使用installModules() ,但这没有帮助。

Am I so wrong to assume that an @Inject on a member is enough to automatically inject it when it is available in the scope and that the order of binding is enough to make previous bindings available without installing in between (like done in ApplicationModule )? 我错误地认为成员上的@Inject足以在范围内可用时自动注入它,并且绑定的顺序足以使之前的绑定可用而不在其间安装(如在ApplicationModule完成)?

If I can provide anything more to make my issue(s) understandable please leave a comment. 如果我可以提供更多信息以使我的问题可以理解,请发表评论。

Thanks in advance! 提前致谢!

Toothpick can only inject dependencies automatically when it creates the instance of the depended object itself (eg it is annotated with @Singleton or there is a direct binding for the class). Toothpick只能在创建依赖对象本身的实例时自动注入依赖项(例如,它使用@Singleton注释或者对类有直接绑定)。

Otherwise you have to manually call Toothpick.inject, just like you do in SimpleTest. 否则你必须手动调用Toothpick.inject,就像在SimpleTest中一样。 There is no way for TP to know when you call the constructor of PlainPojo. 当你调用PlainPojo的构造函数时,TP无法知道。

You could just use 你可以使用

module.bind(PlainPojo.class);
module.bind(SimpleTest.class);

and maybe scope them as singletons if needed. 如果需要,可以将它们作为单身人士的范围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM