Dagger2 没有注入字段

Dagger2 is not injecting field

我有这个模块:

@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() 方法中初始化的注入器 class:

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 的新手,所以任何建议都将不胜感激。

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

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

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

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

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

    void inject(FirstFragment view);

    void inject(SecondFragment view);

}

忘记说 FirstView 和 SecondView 是 interface,不是 class。注入方法需要具体的 class.