Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending ObjectGraph with overriding module

I'm playing with Dagger right now and apparently some of the features don't work for me.

I'm actually trying to extend my ObjectGraph (via ObjectGraph.plus()) with mock module which overrides one of the real modules in already created graph. But apparently my mock module is ignored, so real interfaces are called.

However, if I try to provide my mock module during graph creation stage - everything works fine..

In my case MockModule1 overrides providers from RealModule1

Doesn't work:

objectGraph = ObjectGraph.create(new RealModule1(), 
                                 new RealModule2(), 
                                 new RealModule3());

objectGraph = objectGraph.plus(new MockModule1());

Works fine

objectGraph = ObjectGraph.create(new RealModule1(), 
                                 new RealModule2(), 
                                 new RealModule3(),
                                 new MockModule1());

RealModule1.java

@Module(injects = MainActivity.class)
public class RealModule1 {

    @Provides
    ISomething provideSomething() {
        return new Something();
    }
}

MockModule1.java

@Module(overrides=true, injects = MainActivity.class)
public class MockModule1 {

    @Provides
    ISomething provideSomething() {
        return new MockSomething();
    }
}

Am I missing something?

like image 806
Pavel Dudka Avatar asked Nov 19 '13 01:11

Pavel Dudka


1 Answers

.plus() is a union of two object graphs. The first being provided as the extension point and the right being implicitly created with the passed-in module instances.

overrides=true allows modules to override other dependencies provided within the same object graph.

Overriding will not work when extending an object graph because it wouldn't actually be an override (at least not in the way we define it). Internally, we've been loosely referring to the behavior you describe as "shadowing" and it is something Dagger currently does not support as of the impending v1.2 release.

like image 144
Jake Wharton Avatar answered Nov 19 '22 13:11

Jake Wharton