服务中的依赖注入
Dependency Injection Into Service
我正在尝试 inject dependencies
进入我的应用程序。一切正常,直到我尝试将 Realm
注入我的 Service
class。我开始收到 IllegalStateException
,这显然是我从创建的 Thread
访问 Realm
造成的。所以,这是我的 Dependency Injection
的结构
AppModule
@Module
public class AppModule {
MainApplication mainApplication;
public AppModule(MainApplication mainApplication) {
this.mainApplication = mainApplication;
}
@Provides
@Singleton
MainApplication getFmnApplication() {
return mainApplication;
}
}
RequestModule
@Module
public class RequestModule {
@Provides
@Singleton
Retrofit.Builder getRetrofitBuilder() {
return new Retrofit.Builder()
.baseUrl(BuildConfig.HOST)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(CustomGsonParser.returnCustomParser()));
}
@Provides
@Singleton
OkHttpClient getOkHttpClient() {
return new OkHttpClient.Builder()
.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC))
.connectTimeout(30000, TimeUnit.SECONDS)
.readTimeout(30000, TimeUnit.SECONDS).build();
}
@Provides
@Singleton
Retrofit getRetrofit() {
return getRetrofitBuilder().client(getOkHttpClient()).build();
}
@Provides
@Singleton
ErrorUtils getErrorUtils() {
return new ErrorUtils();
}
@Provides
@Singleton
MainAPI getMainAPI() {
return getRetrofit().create(MainAPI.class);
}
// Used in the Service class
@Provides
@Singleton
GeneralAPIHandler getGeneralAPIHandler(MainApplication mainApplication) {
return new GeneralAPIHandler(mainApplication, getMainAPIHandler(), getErrorUtils());
}
}
AppComponent
@Singleton
@Component(modules = {
AppModule.class,
RequestModule.class
})
public interface MainAppComponent {
void inject(SyncService suncService);
}
应用程序Class
public class MainApplication extends Application {
private MainAppComponent mainAppComponent;
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
@Override
public void onCreate() {
super.onCreate();
mainAppComponent = DaggerMainAppComponent.builder()
.appModule(new AppModule(this))
.requestModule(new RequestModule())
.build();
}
public MainAppComponent getMainAppComponent() {
return mainAppComponent;
}
}
GeneralAPIHandler
public class GeneralAPIHandler {
private static final String TAG = "GeneralAPIHandler";
private MainAPI mainAPI;
private Realm realm;
private ErrorUtils errorUtils;
private Context context;
public GeneralAPIHandler() {
}
public GeneralAPIHandler(MainApplication mainApplication, MainAPI mainAPI, ErrorUtils errorUtils) {
this.mainAPI = mainAPI;
this.realm = RealmUtils.getRealmInstance(mainApplication.getApplicationContext());
this.errorUtils = errorUtils;
this.context = mainApplication.getApplicationContext();
}
public void sendPayload(APIRequestListener apiRequestListener) {
List<RealmLga> notSentData = realm.where(RealmLga.class).equalTo("isSent", false).findAll(); <-- This is where the error comes from
.... Other code here
}
}
只有当我从 Service class
调用它时才会发生这种情况,但是,它是使用应用程序上下文创建的。为什么它会抛出 IllegalStateException
服务Class
public class SyncService extends IntentService {
@Inject GeneralAPIHandler generalAPIHandler;
@Override
public void onCreate() {
super.onCreate();
((MainApplication) getApplicationContext()).getMainAppComponent().inject(this);
}
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*/
public SyncService() {
super("Sync");
}
@Override
protected void onHandleIntent(Intent intent) {
sendInformations();
}
private void sendInformations() {
generalAPIHandler.sendPayload(new APIRequestListener() {
@Override
public void onError(APIError apiError){}
@Override
public void didComplete(WhichSync whichSync){}
})
}
}
任何关于我做错 Realm
throw IllegalStateException
的帮助将不胜感激。谢谢
只需要从创建它的线程访问领域实例。
您的意图服务在后台线程中运行。您的领域可能是在主线程上创建的
@Inject GeneralAPIHandler generalAPIHandler;
@Override
public void onCreate() {
super.onCreate();
((MainApplication) getApplicationContext()).getMainAppComponent().inject(this);
}
因此
public GeneralAPIHandler(MainApplication mainApplication, MainAPI mainAPI, ErrorUtils errorUtils) {
this.mainAPI = mainAPI;
this.realm = RealmUtils.getRealmInstance(mainApplication.getApplicationContext()); // <--
此代码在 UI 线程上运行
@Override
protected void onHandleIntent(Intent intent) {
sendInformations();
}
private void sendInformations() {
generalAPIHandler.sendPayload(new APIRequestListener() {
....
public void sendPayload(APIRequestListener apiRequestListener) {
List<RealmLga> notSentData = realm.where(RealmLga.class).equalTo("isSent", false).findAll();
此代码在 IntentService 后台线程上运行
尽管处于非循环后台线程中,您也不会关闭 Realm 实例,所以崩溃对您有好处。
解决方法,在onHandleIntent()
获取Realm实例,执行结束在finally {
关闭。
你可能会说,"but then how will I mock my Constructor argument",答案是使用 class 比如
@Singleton
public class RealmFactory {
@Inject
public RealmFactory() {
}
public Realm create() {
return Realm.getDefaultInstance();
}
}
我正在尝试 inject dependencies
进入我的应用程序。一切正常,直到我尝试将 Realm
注入我的 Service
class。我开始收到 IllegalStateException
,这显然是我从创建的 Thread
访问 Realm
造成的。所以,这是我的 Dependency Injection
AppModule
@Module
public class AppModule {
MainApplication mainApplication;
public AppModule(MainApplication mainApplication) {
this.mainApplication = mainApplication;
}
@Provides
@Singleton
MainApplication getFmnApplication() {
return mainApplication;
}
}
RequestModule
@Module
public class RequestModule {
@Provides
@Singleton
Retrofit.Builder getRetrofitBuilder() {
return new Retrofit.Builder()
.baseUrl(BuildConfig.HOST)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(CustomGsonParser.returnCustomParser()));
}
@Provides
@Singleton
OkHttpClient getOkHttpClient() {
return new OkHttpClient.Builder()
.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC))
.connectTimeout(30000, TimeUnit.SECONDS)
.readTimeout(30000, TimeUnit.SECONDS).build();
}
@Provides
@Singleton
Retrofit getRetrofit() {
return getRetrofitBuilder().client(getOkHttpClient()).build();
}
@Provides
@Singleton
ErrorUtils getErrorUtils() {
return new ErrorUtils();
}
@Provides
@Singleton
MainAPI getMainAPI() {
return getRetrofit().create(MainAPI.class);
}
// Used in the Service class
@Provides
@Singleton
GeneralAPIHandler getGeneralAPIHandler(MainApplication mainApplication) {
return new GeneralAPIHandler(mainApplication, getMainAPIHandler(), getErrorUtils());
}
}
AppComponent
@Singleton
@Component(modules = {
AppModule.class,
RequestModule.class
})
public interface MainAppComponent {
void inject(SyncService suncService);
}
应用程序Class
public class MainApplication extends Application {
private MainAppComponent mainAppComponent;
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
@Override
public void onCreate() {
super.onCreate();
mainAppComponent = DaggerMainAppComponent.builder()
.appModule(new AppModule(this))
.requestModule(new RequestModule())
.build();
}
public MainAppComponent getMainAppComponent() {
return mainAppComponent;
}
}
GeneralAPIHandler
public class GeneralAPIHandler {
private static final String TAG = "GeneralAPIHandler";
private MainAPI mainAPI;
private Realm realm;
private ErrorUtils errorUtils;
private Context context;
public GeneralAPIHandler() {
}
public GeneralAPIHandler(MainApplication mainApplication, MainAPI mainAPI, ErrorUtils errorUtils) {
this.mainAPI = mainAPI;
this.realm = RealmUtils.getRealmInstance(mainApplication.getApplicationContext());
this.errorUtils = errorUtils;
this.context = mainApplication.getApplicationContext();
}
public void sendPayload(APIRequestListener apiRequestListener) {
List<RealmLga> notSentData = realm.where(RealmLga.class).equalTo("isSent", false).findAll(); <-- This is where the error comes from
.... Other code here
}
}
只有当我从 Service class
调用它时才会发生这种情况,但是,它是使用应用程序上下文创建的。为什么它会抛出 IllegalStateException
服务Class
public class SyncService extends IntentService {
@Inject GeneralAPIHandler generalAPIHandler;
@Override
public void onCreate() {
super.onCreate();
((MainApplication) getApplicationContext()).getMainAppComponent().inject(this);
}
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*/
public SyncService() {
super("Sync");
}
@Override
protected void onHandleIntent(Intent intent) {
sendInformations();
}
private void sendInformations() {
generalAPIHandler.sendPayload(new APIRequestListener() {
@Override
public void onError(APIError apiError){}
@Override
public void didComplete(WhichSync whichSync){}
})
}
}
任何关于我做错 Realm
throw IllegalStateException
的帮助将不胜感激。谢谢
只需要从创建它的线程访问领域实例。
您的意图服务在后台线程中运行。您的领域可能是在主线程上创建的
@Inject GeneralAPIHandler generalAPIHandler;
@Override
public void onCreate() {
super.onCreate();
((MainApplication) getApplicationContext()).getMainAppComponent().inject(this);
}
因此
public GeneralAPIHandler(MainApplication mainApplication, MainAPI mainAPI, ErrorUtils errorUtils) {
this.mainAPI = mainAPI;
this.realm = RealmUtils.getRealmInstance(mainApplication.getApplicationContext()); // <--
此代码在 UI 线程上运行
@Override
protected void onHandleIntent(Intent intent) {
sendInformations();
}
private void sendInformations() {
generalAPIHandler.sendPayload(new APIRequestListener() {
....
public void sendPayload(APIRequestListener apiRequestListener) {
List<RealmLga> notSentData = realm.where(RealmLga.class).equalTo("isSent", false).findAll();
此代码在 IntentService 后台线程上运行
尽管处于非循环后台线程中,您也不会关闭 Realm 实例,所以崩溃对您有好处。
解决方法,在onHandleIntent()
获取Realm实例,执行结束在finally {
关闭。
你可能会说,"but then how will I mock my Constructor argument",答案是使用 class 比如
@Singleton
public class RealmFactory {
@Inject
public RealmFactory() {
}
public Realm create() {
return Realm.getDefaultInstance();
}
}