2015-11-19 160 views
0

我检查了所有问题,但没有发现任何线索。我剥夺了我的问题,以一个简单的代码:匕首2不注入依赖模块

情况: 我想有:

CatComponent catComponent = DaggerCatComponent.builder() 
     .kameModule(new KameModule(MainActivity.this)) 
     .build(); 
    catComponent.getCatAnalyzer().analyze(); 

我已经创建的组件:

@Component(modules = {KameModule.class, CatAnalyzerModule.class}) 
public interface CatComponent { 

    CatAnalyzer getCatAnalyzer(); 
} 

和模块:

@Module 
public class KameModule { 

    private Context context; 

    public KameModule(Context context) { 
     this.context = context; 
    } 

    @Provides 
    KameCat provideKameCat() { 
     return new KameCat(context); 
    } 
} 

@Module(includes = KameModule.class) 
public class CatAnalyzerModule { 

    @Inject 
    KameCat cat; 

    @Provides 
    CatAnalyzer provideCatAnalyzer() { 
     return new CatAnalyzer(cat); 
    } 
} 

和类:

public class KameCat { 

    Context context; 

    public KameCat(Context context) { 
     this.context = context; 
    } 

    public void doCatStuff() { 
     Toast.makeText(context, "Poo and Meow", Toast.LENGTH_LONG).show(); 
    } 
} 

public class CatAnalyzer { 

    @Inject 
    KameCat cat; 

    @Inject 
    public CatAnalyzer(KameCat cat) { 
     this.cat = cat; 
    } 

    void analyze() { 
     cat.doCatStuff(); 
    } 
} 

当我从CatComponent找回我的CatAnalyzer对象有cat清零。 我不知道为什么Dagger不会注入它。你能指导我吗?

回答

2

正确代码:

@Module(includes = KameModule.class) 
public class CatAnalyzerModule { 

    @Inject //remove this 
    KameCat cat;// remove this 

    @Provides 
    // Add cat as a argument and let KameModule provide it.. 
    CatAnalyzer provideCatAnalyzer(KameCat cat) { 
     return new CatAnalyzer(cat); 
    } 
} 

感谢:因为在`CatAnalyzerModule`所提供的类 https://www.future-processing.pl/blog/dependency-injection-with-dagger-2/

+0

你'@ Inject'注解的是多余的。你可以从模板中删除模块,或者在构造函数中使用@Inject注解。无论哪种方式,“KameCat猫”上的“@ Inject”注释都是多余的。 – rdshapiro

+0

此外,对于更多习惯性的DependencyInjection,“KameModule”将提供上下文,以便它可以参与任何模块中的任何地方。然后,'provideKameCat'方法也可以使用'Context'作为参数,类似于你使用'provideCatAnalyzer(KameCat cat)'做的事情' – rdshapiro

+0

'最后,如果你结束,'@ Module.includes'不是必须的包括两个模块在'@ Component.modules'列表中。 – rdshapiro