异步对象未向get_it

时间:2019-11-28 16:25:14

标签: asynchronous flutter dart dependency-injection inversion-of-control

我正在将get_it用于IoC。但是,当我尝试使用异步调用注册Bean时,我的应用程序引发了异常。 引发异常的函数:

import 'package:elpee/service/localstorage_service.dart';
import 'package:get_it/get_it.dart';


GetIt locator = GetIt();
Future setupLocator() async {
  LocalStorageService.getInstance().then((storageService) {
    locator.registerSingleton(storageService);
  });
}

错误: Exception: Object of type LocalStorageService is not registered inside GetIt

如果有人可以帮助我,我将不胜感激:-)

1 个答案:

答案 0 :(得分:4)

您正在尝试以错误的方式使用get_it。选中documentation

首先-get_it是Singleton,因此不要使用构造函数,但是

void main()
...
   void setupLocator() {
     locator.registerLazySingleton(LocalStorageService());
   }
}

第二个-将LocalStorageService实现为一个普通类,并让get_it将其作为Singleton提供:

void setupLocator() {
  locator.registerLazySingleton<IStorageService>(LocalStorageService());
}

要充分利用IoC的强大功能为存储服务定义接口/抽象类定义,并提供接口的实现。

def get_task_products(task_id):
    before = time.time()
    session = get_new_session()

    persisted_task_products =session.query(TaskProducts). \
        filter(TaskProducts.task_id == task_id). \
        options(load_only(TaskProducts.product_id)).all()
    df = pd.DataFrame(persisted_task_products)
    df.columns = persisted_task_products[0].keys()
    print_debug(
        'db_manager.persisted_motionlesstime: query result (after {0} seconds) : {1})'. \
            format(time.time() - before, df))

    if not df or len(df) != 0:
        return df
    session.close()