【问题标题】:Dagger2 is not injecting fieldDagger2 没有注入字段
【发布时间】:2016-07-06 14:22:24
【问题描述】:

我有这个模块:

@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(即Fragments)中,我有这个:

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

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

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

我在“provides”模块的方法中设置了断点,providesFirstController 被执行但providesSecondController 没有被执行。

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

【问题讨论】:

  • 你在哪里打电话initialize(App app)
  • App.onCreate() 方法中。 App 是我扩展 Application 的类
  • 在片段的构造函数中调用inject()
  • 它不起作用:(
  • 请分享您的 MainModule.java 。

标签: android dagger-2


【解决方案1】:

如果是Fragments,请尝试移动与注入相关的代码:

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

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

【讨论】:

    【解决方案2】:

    解决了!我已将inject 方法的签名更改为:

    @Singleton
    @Component(modules = MainModule.class)
    public interface MainComponent {
    
        void inject(FirstFragment view);
    
        void inject(SecondFragment view);
    
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多