我想使用匕首(Square匕首v1)创建一个单例类,其构造函数需要上下文作为参数.然后,我想将此单例类注入到MainActivity中.定义此步骤的正确步骤是什么?
我尝试这样做:
SingletonClass:
@Module(
injects = {MainActivity.class}
)
@Singleton
public class SingletonClass {
...
@Inject
SingletonClass(Context ctx) {}
}
我收到的错误:
no injectable members on android.content.Context
我知道SingletonClass应该从某个地方接收它的上下文以便被注入,但是由于我不再以传统意义“调用”它,而是像在MainActivity中那样在类中注入它-水平:
@Inject SingletonClass singletonClass;
我应该如何传递上下文?
这是我为匕首创建的其他文件(在官方示例中看到了其中两个):
AndroidModule:
@Module(library = true, injects = MainActivity.class)
public class AndroidModule {
private final Context context;
public AndroidModule(Context context) {
this.context = context;
}
/**
* Allow the application context to be injected but require that it be
* annotated with to explicitly
* differentiate it from an activity context.
*/
@Provides
@Singleton
@ForApplication
Context provideApplicationContext() {
return context;
}
}
App.class(扩展我的应用程序):
public class App extends Application {
private static final String TAG = App.class.getSimpleName();
private static App instance;
public MainActivity mainActivity;
private static Context context;
private ObjectGraph objectGraph;
public void onCreate() {
super.onCreate();
instance = this;
context = getApplicationContext();
objectGraph = ObjectGraph.create(getModules().toArray());
}
public static App getInstance() {
return instance;
}
public static Context getContext() { return context; }
protected List<Object> getModules() {
return Arrays.asList(new AndroidModule(this), new App());
}
public void inject(Object object) {
objectGraph.inject(object);
}
}
ForApplication类:
import java.lang.annotation.Retention;
import javax.inject.Qualifier;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Qualifier @Retention(RUNTIME)
public @interface ForApplication {
}
解决方法:
您需要将@ForApplication限定词添加到SingletonClass构造函数中的Context参数中.
Dagger现在正在寻找要注入的上下文,但是只有@ForApplication Context,这是不匹配的.
@Singleton
public class SingletonClass {
@Inject
SingletonClass(@ForApplication Context ctx) {
}
}
现在,您还可以摆脱AndroidModule中的library = true行,您可能已经添加了它,因为Dagger警告您@ForApplication Context未使用(不要忽略这些警告!).
另外,这可能只是复制粘贴错误,此SingletonClass不应具有@Module批注.