AuthRepository -> AuthDataSource -> ApiClient -> AuthInterceptor -> AuthRepository
这里的目标是在AuthInterceptor中实现网络请求拦截。具体来说,如果响应代码是 401(表示未验证状态),拦截器应该触发对 AuthRepository.logout() 的调用。
代码:
final sl = GetIt.instance; // sl is short for service locator
sl.registerLazySingleton<AuthInterceptor>(() => AuthInterceptor(authRepository: sl()));
sl.registerLazySingleton<ApiClient>(
() => ApiClient(dio: Dio(), preferencesService: sl(), authInterceptor: sl(), tokenStorage: sl()));
sl.registerLazySingleton<AuthRepository>(() => AuthRepositoryImpl(authDataSource: sl()));
sl.registerLazySingleton<AuthDataSource>(() => AuthRemoteDataSourceImpl(apiClient: sl()));
我也有同样的问题。这个答案有帮助。您可以在类中使用 GetIt,只需不要将对象发送到构造函数中即可。