user3057944 user3057944 - 2 months ago 7
Java Question

How to inject object with args in it's constructor with Dagger2

update

Now I modified my code like this, and it works, but I don't know is this the proper way.

the class http://pastebin.com/srhu4eB7

this is the injection http://pastebin.com/wLbxBQqb

I'm learning how to use dagger2 in my project, but I don't know how to inject this dependency.
I have a test calss with a constructor where I've to pass 3 args that comes from the activity where to I want to inject my class.
Here is my test class: http://pastebin.com/XqRNFbvj
Here is my module for my test class: http://pastebin.com/r4wmqfLB and this is my component: http://pastebin.com/r1QYdNJx

and here how I'd like to use the injection, but it isn't work: http://pastebin.com/cs0V5wfq

Can I somehow inject objects like this, or how can I pass args to injected object?

Answer

If you don't have any other dependency in this class, then maybe it's not really a dependency of your activity and you could just use a new. But to answer your question, you'd want to have a subcomponent for your activity (or activities of this kind) with a module like this:

@Module
public class TestModule {
  private final String arg1;
  private final int arg2;
  private final boolean arg3;

  public TestModule(String arg1, int arg2, boolean arg3) {
    this.arg1 = arg1;
    this.arg2 = arg2;
    this.arg3 = arg3;
  }

  @Provides DaggerTestClass provideDaggerTestClass() {
    return new DaggerTestClass(arg1, arg2, arg3);
  }
}

and you'd use it like:

IndexApplication.getApplication().getAppComponent()
    .daggerTestSubcomponent(new DaggerTestModule("arg1", 2, true))
    .inject(this);

If you have other dependencies in this class though, then you'd probably want to actually use a factory (possibly generated for you using AutoFactory), then "manually inject" the created object:

private DaggerTestClass daggerTestClass; // note: no @Inject here

// …

// Inject other dependencies into the activity
IndexApplication.getApplication().getAppComponent().inject(this);
// "manually inject" the DaggerTestClass
this.daggerTestClass = IndexApplication.getApplication().getAppComponent()
    .daggerTestFactory().create("arg1", 2, true);
Comments