如何在仍使用Dagger2的情况下解决循环依赖关系? [英] How to resolve a circular dependency while still using Dagger2?

查看:233
本文介绍了如何在仍使用Dagger2的情况下解决循环依赖关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个类,分别是 Foo< T> Bar 其他各种课程。我正在使用Dagger-2进行依赖项注入,但是如果我天真地添加循环依赖项,Dagger在运行时会遇到堆栈溢出。重构类以解决此问题的一种好方法,同时仍使用Dagger注入所有其他依赖项,并以最小的重复和对现有调用的更改来实现?

I have two classes, Foo<T> and Bar, which depend on each other, as well as various other classes. I am using Dagger-2 for dependency injection, but if I naively add the circular dependency, Dagger hits a stack overflow at runtime. What's a good way to refactor the classes to fix this, while still using Dagger to inject all the other dependencies, and with minimal duplication and changes to existing calls?

推荐答案

简单的解决方法是在一侧使用 Lazy< T>

The easy way out is to use Lazy<T> on one side.

Lazy<Foo> foo;

@Inject
Bar(Lazy<Foo> foo) {
    this.foo = foo;
}

// use foo.get(); when needed

这篇关于如何在仍使用Dagger2的情况下解决循环依赖关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆