如何解决Flutter中的这种循环依赖

问题描述 投票:0回答:1

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()));
flutter dart dependency-injection circular-dependency
1个回答
0
投票

我也有同样的问题。这个答案有帮助。您可以在类中使用 GetIt,只需不要将对象发送到构造函数中即可。

© www.soinside.com 2019 - 2024. All rights reserved.