首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Dagger-2:如果我必须在运行时注入依赖项,如何连接我的程序?

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

Stack Overflow用户
提问于 2018-09-18 21:35:25
回答 1查看 527关注 0票数 0

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

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

代码语言:javascript
复制
@Component(modules = {
    ModuleApplication.class,
    ModuleUtils.class
})
public interface ComponentApplication {
   ComponentSocketManager.Builder componenetSocketManagerBuilder();
}

我的子组件(用于创建SocketManager)

代码语言:javascript
复制
@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:

代码语言:javascript
复制
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的继承概念呢?或者,当我在运行时需要注入依赖项时,如何避免中断整个程序的连接过程?

EN

回答 1

Stack Overflow用户

发布于 2018-09-20 00:51:02

当你的父组件有一个ObjectMapper的绑定时,你的子组件就有权访问它。这意味着您可以在您的子组件中创建供应方法,如...

代码语言:javascript
复制
@Subcomponent(modules = {SubcomponentModule.class})
public interface MySubcomponent {
    ...
    ObjectMapper objectMapper(); // e.g. singleton bound by parent component
    ...
}

并且您可以在子组件模块中依赖这样的对象

代码语言:javascript
复制
@Module
public class SubcomponentModule {
    @Provides
    Foo provideFoo(ObjectMapper objectMapper) {
        return new Foo(objectMapper);
    }
}

另请参阅Dagger Subcomponents

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52387839

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档