我想用Dagger 2和MVP模式.所以我有这个场景,每个View
都有它自己的Component
例如 MyFragment
有这样的组件:
@PerFragment @Component(dependencies = ActivityComponent.class, modules = MyFragmentModule.class) public interface MyFragmentComponent { void inject(MyFragment fragment); }
在MyFragmentModule
,我提供了一个演示者和一个将用于的模型MyFragment
@Module public class MyFragmentModule { @Provides @PerFragment public MyPresenter providePresenter() { return new MyPresenter(); } @Provides @PerFragment public Model provideModel() { return new Model(); } }
现在我正在注入组件MyFragment
:
public class MyFragment extends Fragment{ @Inject MyPresenter presenter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); component = DaggerMyFragmentComponent.builder()...build(); component.inject(this); } }
也是MyPresenter
这样的:
public class MyPresenter { @Inject Model model; }
题
我不知道如何Model
在我的演示者中注入.我不想像我所做的那样在我的演示者中注入一个组件MyFragment
.
这种方法有什么办法吗?
考虑必须通过组件手动调用字段注入,您需要对组件的引用.当然,您不应该在Presenter中合法地创建新组件,我认为您应该做的是提供包含组件引用的类.
请检查编辑以获得正确的解决方案.
@Module public class MyFragmentModule { private MyFragment myFragment; public MyFragmentModule(MyFragment myFragment) { this.myFragment = myFragment; } @Provides public MyFragment myFragment() { return myFragment; } @Provides @PerFragment public MyPresenter providePresenter(MyFragment myFragment) { return new MyPresenter(myFragment); } @Provides @PerFragment public Model provideModel(MyFragment myFragment) { return new Model(myFragment); } } public class MyPresenter { @Inject Model model; public MyPresenter(MyFragment myFragment) { myFragment.getComponent().inject(this); } }
你的另一种选择是构造函数注入.
public class MyPresenter { private Model model; public MyPresenter(Model model) { this.model = model; } } @Provides @PerFragment public MyPresenter providePresenter(Model model) { return new MyPresenter(model); }
编辑:第三种解决方案是使用Presenter完全跳过模块,只使用带@Inject
注释的构造函数.
@PerFragment public class MyPresenter { private Model model; @Inject public MyPresenter(Model model) { this.model = model; } }
要么
@PerFragment public class MyPresenter { @Inject Model model; @Inject public MyPresenter() { } }