質問

I'm processing an annotation that has a type parameter. This type parameter is used to instantiate a new object.

With Google Guice, I'd inject the 'Injector' itself and use that to find the correct instance. However I'm a bit new to Dagger and I don't see any solutions described on the net. I know that the ObjectGraph can give me an instance. Can I/am I allowed to inject the ObjectGraph itself? How would I do that?

役に立ちましたか?

解決

I managed to do it like this. Not sure if it is good...

Bar:

public class Bar {

    private ObjectGraph objectGraph;

    @Inject
    Bar(ObjectGraph objectGraph){

        this.objectGraph = objectGraph;
    }

    public ObjectGraph getObjectGraph() {
        return objectGraph;
    }
}

BarModule:

@Module(
        injects = Bar.class,
        complete = false
)
public class BarModule {
}

FooModule:

@Module(
        includes = BarModule.class,
        injects = ObjectGraph.class,
        complete = true,
        library = true
)
public class FooModule {

    private ObjectGraph objectGraph;

    public void setObjectGraph(ObjectGraph objectGraph){

        this.objectGraph = objectGraph;
    }

    @Provides @Singleton ObjectGraph providesObjectGraph(){
        return null;
    }
}

EntryPoint:

public class EntryPoint {

    public static void main(String[] args){
        FooModule fooModule = new FooModule();
        ObjectGraph objectGraph = ObjectGraph.create(new BarModule(), fooModule);
        fooModule.setObjectGraph(objectGraph);

        System.out.println(objectGraph);

        Bar bar = objectGraph.get(Bar.class);
        ObjectGraph objectGraph1 = bar.getObjectGraph();

        System.out.println(objectGraph);
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top