Dagger-2:如果我必须在运行时注入依赖项,如何连接我的程序?



我认为这是一个非常基本的问题,我找不到答案。我的设置如下:

我的主要组件(用于使依赖项可用于整个对象图,例如Jackson的ObjectMapper.class,由ModuleUtils.class提供(

@Component(modules = {
ModuleApplication.class,
ModuleUtils.class
})
public interface ComponentApplication {
ComponentSocketManager.Builder componenetSocketManagerBuilder();
}

我的子组件(用于创建套接字管理器(

@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 的帮助下实例化新的套接字管理器:

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有一个ObjectMapper-dependencies。如何为我的"appBusinessLogic"对象重用该实例?当然,我可以像ComponentAppBusinessLogic一样,继承自ComponentApplication。但是,使用 ComponentAppBusinessLogic 创建一个 "appBusinessLogic" 对象会导致一个新的 ObjectMapper-dependency?
那么,如何在初始化阶段连接整个程序并使用 dagger 的继承概念呢?或者,当我在运行时要注入依赖项时,如何避免中断整个程序的布线过程?

当您的父组件具有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);
}
}

另请参阅dagger子组件

最新更新