我开始使用匕首,就像它一样,但现在面临一些困难。我的场景如下:有一个活动和一个依赖项。依赖关系被注入活动,并需要引用该活动。就像这样:
public class MainActivity extends BaseActivity {
@Inject ScbeHelper scbeHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
}
}
public class ScbeHelper {
protected static final String TAG = "scbe_helper";
private BaseActivity activityContext;
@Inject
public ScbeHelper(BaseActivity context) {
this.activityContext = context;
}
}
我正在关注活动图表的dagger's example from the github。所以我在我的项目中创建了一个类似的结构。首先,继承BaseActivity
的{{1}}类:
MainActivity
模块:
public abstract class BaseActivity extends Activity {
private ObjectGraph activityGraph;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
protoApp application = (protoApp) getApplication();
// Exception happens in next line, inside plus() method
activityGraph = application.getApplicationGraph().plus(getModules().toArray());
// Inject ourselves so subclasses will have dependencies fulfilled when this method returns.
activityGraph.inject(this);
((protoApp)getApplication()).inject(this);
}
protected List<Object> getModules() {
return Arrays.<Object>asList(new ActivityModule(this));
}
public void inject(Object object) {
activityGraph.inject(object);
}
}
现在,问题是: @Module(injects={MainActivity.class})
public class ActivityModule {
private final BaseActivity activity;
public ActivityModule(BaseActivity activity) {
this.activity = activity;
}
@Provides @Singleton BaseActivity provideActivity() {
return activity;
}
}
换句话说,提供程序方法No injectable members on com.example.proto.BaseActivity. Do you want to add an injectable constructor? required by public com.example.proto.ScbeHelper(com.example.proto.BaseActivity)
由于某种原因并不真正提供ActivityModule.provideActivity()
的实例,但在我的理解中它已正确设置。有没有人在我的设置中看到错误?我错过了匕首的逻辑吗?
提前致谢!
答案 0 :(得分:2)
我不是Dagger的专家,但你有两个问题:
以下是我为了让它发挥作用所做的事情:
@Provides @Singleton ScbeHelper provideScbeHelper() {
return new ScbeHelper(activity);
}
它的作用是为ScbeHelper提供所需的上下文,但只留下1个注释驱动的注入,因此dagger可以解决它。希望这会有所帮助。