2016-07-06 66 views
0

我有这样的模块:Dagger2不注入字段

@Module 
public class MainModule { 

    private Context context; 

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

    @Provides 
    @Singleton 
    Dao providesDao() { 
     return new Dao(); 
    } 

    @Provides 
    @Singleton 
    FirstController providesFirstController(Dao dao) { 
     return new FirstController(dao); 
    } 

    @Provides 
    @Singleton 
    SecondController providesSecondController(Dao dao) { 
     return new SecondController(dao); 
    } 

} 

并且该组分:

@Singleton 
@Component(modules = MainModule.class) 
public interface MainComponent { 

    void inject(FirstView view); 

    void inject(SecondView view); 

} 

,最后,该喷射器类中,在App.onCreate()方法初始化:

public enum Injector { 

    INSTANCE; 

    MainComponent mainComponent; 

    public void initialize(App app) { 
     mainComponent = DaggerMainComponent.builder() 
       .mainModule(new MainModule(app)) 
       .build(); 
    } 

    public MainComponent getMainComponent() { 
     return mainComponent; 
    } 
} 

在我的FirstView和SecondView(即Fragment s)中,我有这个:

@Inject 
    FirstController controller; //and SecondController for the second view 

    @Override 
    public void onAttach(Context context) { 
     super.onAttach(context); 
     Injector.INSTANCE.getMainComponent().inject(this); 
    } 

在第一个片段中,一切正常,控制器被注入。但在第二种观点中,它不是:仅返回null

我已经在“提供”模块的方法中放置了断点,并且执行了providesFirstController而不是providesSecondController

我在做什么错?我是Dagger2的新手,所以任何建议将不胜感激。

+0

你在哪里调用'initialize(App app)'? – znat

+0

在'App.onCreate()'方法中。应用程序是我的类扩展应用程序 –

+0

在片段的构造函数调用'inject()' – EpicPandaForce

回答

0

解决!我有inject方法的签名更改为:

@Singleton 
@Component(modules = MainModule.class) 
public interface MainComponent { 

    void inject(FirstFragment view); 

    void inject(SecondFragment view); 

} 

我忘了说的firstView和SecondView是interface S,而不是类。注入方法需要具体的类。

0

如果这些是Fragments尝试移动与注射连接的代码:

Injector.INSTANCE.getMainComponent().inject(this); 

Fragmentpublic void onCreate(Bundle savedInstanceState)方法。 如果视图在屏幕上不可见(同时添加FragmentManager),则可能不会调用方法。

+0

感谢您的答案。它仍然无法正常工作 –