我认为这是一个非常基本的问题,我找不到答案。我的设置如下:
我的主要组件(用于使依赖项对整个对象图可用,例如由ModuleUtils.class提供的Jackson's ObjectMapper.class )
@Component(modules = {
ModuleApplication.class,
ModuleUtils.class
})
public interface ComponentApplication {
ComponentSocketManager.Builder componenetSocketManagerBuilder();
}我的子组件(用于创建SocketManager)
@Subcomponent(modules = ModuleSocketManager.class)
public interface ComponentSocketManager {
//Subcomponent is used to create a SocketManager
SocketManager socketManager();
@Subcomponent.Builder
interface Builder {
//SocketManager requires a Socket to work with, which is only
//available at runtime
@BindsInstanceBuilder socket(Socket socket);
ComponentSocketManager build();
}
}在程序运行时,套接字被派生出来,并且可以在Dagger2的帮助下实例化新的SocketManagers:
Socket socket = this.serverSocket.accept();
//Here the wiring of the object graph is somehow interrupted, as I need
//to inject objects at runtime, that are required for the wiring process
SocketManager sm = DaggerComponentApplication.create()
.componenetSocketManagerBuilder()
.socket(socket) //inject the socket at runtime
.build()
.socketManager();
//I don't want to wire my app manually. Dagger should do the wiring of the
//entire object graph, not only up to the point where I inject at runtime
AppBusinessLogic appBusinessLogic = ... //some deeply nested wiring
MyApp app = new MyApp(sm, appBusinessLogic);
Thread thread = new Thread(app); //new thread for every client
thread.start();问题是我如何手动干预dagger2的“连接过程”,以及AppBusinessLogic是如何创建的。AppBusinessLogic基本上代表了整个程序,是一个深度嵌套的对象图。
我想要的:
在启动时初始化整个程序(不“中断”连接过程)。相反,在运行时将依赖项注入到包含运行时依赖项的某种“占位符”的完整对象图中。
我为什么要那样做呢?
我想重用父组件中的依赖项。例如,在上面的例子中,ComponentApplication有一个对象映射器依赖项。我如何为我"appBusinessLogic“对象重用这个实例呢?当然,我也可以继承自ComponentApplication的ComponentAppBusinessLogic之类的东西。然而,使用ComponentAppBusinessLogic创建一个“appBusinessLogic”依赖项会导致一个新的对象映射器依赖吗?
那么,我如何在初始化阶段连接整个程序,并使用dagger的继承概念呢?或者,当我在运行时需要注入依赖项时,如何避免中断整个程序的连接过程?
发布于 2018-09-20 00:51:02
当你的父组件有一个ObjectMapper的绑定时,你的子组件就有权访问它。这意味着您可以在您的子组件中创建供应方法,如...
@Subcomponent(modules = {SubcomponentModule.class})
public interface MySubcomponent {
...
ObjectMapper objectMapper(); // e.g. singleton bound by parent component
...
}并且您可以在子组件模块中依赖这样的对象
@Module
public class SubcomponentModule {
@Provides
Foo provideFoo(ObjectMapper objectMapper) {
return new Foo(objectMapper);
}
}https://stackoverflow.com/questions/52387839
复制相似问题