如何注入与参数对象在它的构造与Dagger2

问题描述:

更新如何注入与参数对象在它的构造与Dagger2

现在我修改了这样的代码,它的作品,但我不知道这是正确的方式。

http://pastebin.com/srhu4eB7

这是注射http://pastebin.com/wLbxBQqb

我正在学习如何在我的项目中使用dagger2,但我不知道如何注入这种依赖性。 我有一个构造函数的测试calss,我必须通过来自活动的3个参数,我要注入我的类。 这里是我测试类http://pastebin.com/XqRNFbvj 这里是我的测试类我模块http://pastebin.com/r4wmqfLB,这是我组件http://pastebin.com/r1QYdNJx
这里我想如何使用注射,但它是不是工作:http://pastebin.com/cs0V5wfq

我可以以某种方式注入像这样的对象,或者我怎样才能通过参数注入对象?

如果您在此课程中没有任何其他依赖项,那么您的活动可能不是依赖项,您可以使用new。但是,为了回答你的问题,你想为你的活动与这样的模块子(或这类活动):

@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); 
    } 
} 

和你使用它像:

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

如果你在这个类有其他的依赖,虽然,那么你可能想实际使用工厂(您使用AutoFactory对可能产生的),然后在“手动进”创建的对象:

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); 
+0

谢谢,我需要广告依赖注入,我只是举了一个例子来描述为什么我不能注入我现有的类。我想这就是我想要的。 – user3057944

+0

我试图实现你建议的解决方案,但我没有方法.daggerTestFactory() – user3057944

+0

的确,你必须添加它! (或者将它注入到你的活动中,但是因为你只会用它来初始化另一个域......) –