模块取决于Dagger中的另一个模块

模块取决于Dagger中的另一个模块,第1张

模块取决于Dagger中的另一个模块

您无需在一个模块中显式地进行任何注入(字段或构造函数)。只需使用

addsTo
和即可
includes

includes
允许将模块添加到另一个模块并使用它们提供的所有内容。例:

@Module()public class ModuleA {    @Provides @Named("ValueA") String providevalueA() {        return "This is ValueA";    }}@Module(    includes = ModuleA.class)public class ModuleB {    // ValueA comes from ModuleA    @Provides @Named("ValueB") String providevalueB(@Named("ValueA") String valueA) {        return valueA + " and ValueB";    }}

addsTo
与一起使用
ObjectGraph.plus(Object...modules)
。当图形已经创建并包含一些模块时(例如在Application类中),您可以使用创建新图形(例如在Activity中)
plus
。例:

@Module()public class ApplicationModule {    @Provides @Named("ValueA") String providevalueA() {        return "This is ValueA";    }}@Module(    addsTo = ApplicationModule.class)public class ActivityModule {    // ValueA comes from ApplicationModule    @Provides @Named("ValueB") String providevalueB(@Named("ValueA") String valueA) {        return valueA + " and ValueB";    }}public class DemoApplication extends Application {  private ObjectGraph graph;  @Override public void onCreate() {     super.onCreate();     graph = ObjectGraph.create(getModules().toArray());  }  protected List<Object> getModules() {      return Arrays.asList(          new ApplicationModule()      );  }  public void inject(Object object) {      graph.inject(object);  }  public ObjectGraph getObjectGraph() {      return graph;  }}public class DemoActivity extends Activity {    private ObjectGraph activityGraph;    @Override protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        // Create the activity graph by .plus-ing our modules onto the application graph.        DemoApplication application = (DemoApplication) getApplication();        activityGraph = application.getApplicationGraph().plus(new ActivityModule());        // Inject ourselves so subclasses will have dependencies fulfilled when this method returns.        activityGraph.inject(this);    }    @Override protected void onDestroy() {        // Eagerly clear the reference to the activity graph to allow it to be garbage collected as        // soon as possible.        activityGraph = null;        super.onDestroy();    }}

您也可以检查此示例以创建图形范围。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5561740.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-14
下一篇 2022-12-14

发表评论

登录后才能评论

评论列表(0条)

保存