在不完整的父级上追踪Dagger .plus()

Bit*_*nce 5 java dependency-injection dagger

考虑一个Dagger模块:

@Module(library = true, complete = false)
public static class Module {
    @Provides
    public Contextualized providesContextualized(Context ctx) {
        return new Contextualized(ctx.getUsername());
    }
    // ... and many more such provides.
}
Run Code Online (Sandbox Code Playgroud)

Context是一个对象可能连接到例如在启动时无法知道的HTTP会话,当一个人通常会创建一个图形时:

@Module(library = true, complete = false)
public static class ContextModule {
    private final String username;
    public ContextModule(String username) { this.username = username; }

    @Provides
    public Context providesContext() {
        return new Context() {
            public String getUsername() { return username; }
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

鉴于Module足够长,首先为Module创建一个图表似乎是有意义的:

ObjectGraph baseline = ObjectGraph.create(new Module());
Run Code Online (Sandbox Code Playgroud)

然后,在处理特定请求时,创建一个使图形完整的唯一图形:

ObjectGraph withContext = baseline.plus(new ContextModule("killroy"));
Run Code Online (Sandbox Code Playgroud)

但是,.plus()似乎假设继承的图形是完整的:

java.lang.IllegalStateException: Errors creating object graph:
Context could not be bound with key Context required by class PlusExample$Module
at dagger.internal.ThrowingErrorHandler.handleErrors(ThrowingErrorHandler.java:34)
at dagger.internal.Linker.linkRequested(Linker.java:182)
at dagger.internal.Linker.linkAll(Linker.java:109)
at dagger.ObjectGraph$DaggerObjectGraph.linkEverything(ObjectGraph.java:244)
at dagger.ObjectGraph$DaggerObjectGraph.plus(ObjectGraph.java:203)
at PlusExample.plusFailsOnIncompleteModule(PlusExample.java:46)
Run Code Online (Sandbox Code Playgroud)

我是否误解了.plus()在Dagger中的作用是什么?是否有其他直接的方式将用户推迟到图表中?(如果Module中的每个提供都必须从threadlocal或其他类似的东西中查找用户,那将会很烦人.)

ilu*_*luu 1

看起来像是您问题的答案:https ://github.com/square/dagger/issues/384

希望有帮助!