2016-09-22 60 views
0

更新如何注入與參數對象在它的構造與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

我可以以某種方式注入像這樣的對象,或者我怎樣才能通過參數注入對象?

回答

1

如果您在此課程中沒有任何其他依賴項,那麼您的活動可能不是依賴項,您可以使用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

的確,你必須添加它! (或者將它注入到你的活動中,但是因爲你只會用它來初始化另一個域......) –

相關問題