سؤال

I'm trying to use Dagger for my android project but I encounter a Problem: Is it possible to mix constructor and field injection? I have a module and two classes:

@Module(injects = fooActivity.class)
public class Module {
    private fooActivity activity;

    public Module(fooActivity activity) {
        this.activity = activity;
    }

    @Provides
    public bar provideBar() {
        return new bar(activity);
    } 
}

public class fooActivity extends Activity {

    @Inject Baz baz;
    public void onCreate(Bundle savedInstanceState) {
        ...
        ObjectGraph graph = ObjectGraph.create(new BasicModule()).plus(new Module(this));
        graph.inject(this);
    }
}

public class bar {

    @Inject Baz baz;
    @Inject FooActivity activity;
    public bar(FooActivity activity) {
        this.activity = activity;
    }
}

The problem is that 'baz' in the class 'Bar' is always null after the injection. It works though, if I don't use a provide method but only use field injection and handle all dependencies in 'Module'. So from my point of view there are three possibilities: 1) Do field injection only and handle all dependencies in module classes. 2) Do constructor injection only and have all dependencies as constructor parameters. 3) Mix both but call .inject(this) on a ObjectGraph-object in the constructor to satisfy fields with @Inject annotation.

Is this correct?

EDIT: I cannot use complete constructor injection because 'baz' is declared in another module. Editing the example.

@Module(includes = Module.class)
public class BasicModule {
    @Provides 
    public baz provideBaz() {
        return new baz();
    }
}
هل كانت مفيدة؟

المحلول

I think what you are trying to do is possible. I think you want to add your activity graph to your main application graph in dagger.

Check out https://github.com/square/dagger/tree/master/examples/android-activity-graphs.

Also your class bar, you should probably do complete constructor injection. But if you MUST do it the way you are doing, you need to call inject and register bar in a module. Here is the way I would create Bar.

public class Bar {
    private final Activity activity;
    private final Baz baz;

    @Inject public bar(FooActivity activity, Baz baz) {
        this.activity = activity;
        this.baz = baz;
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top