异步工厂的依赖注入分辨率

时间:2017-01-13 00:26:52

标签: dependency-injection dart

通过di.dart包将数据库连接注入到类中时遇到一些问题。具体来说,解决toFactory选项中的异步依赖关系。 两次尝试都会产生

NoSuchMethodError: Class '_Future' has no instance method 'query'.

错误,并且不清楚正确的前进道路。我宁愿保留conn属性而不包含在Future中。我曾尝试在类构造函数中展开Future,但此时不允许在Dart中使用异步构造函数。

import 'package:postgresql/pool.dart';
import 'package:postgresql/postgresql.dart';
import 'package:di/di.dart';

main() async {
  var uri = "postgres://username:password@localhost:5432/database";
  var pool = new Pool(uri, minConnections: 2, maxConnections: 5);
  await pool.start();

  Module module = new Module();
  module.bind(TestQuery);
  module.bind(TestController);
  module.bind(Pool, toValue: pool);
  module.bind(Connection, toFactory: (pool) => pool.connect(), inject: [Pool]);

  var injector = new ModuleInjector([module]);

  var html = await injector.get(TestController).index(); 
  print(html);
}

class BaseQuery {
  Connection conn;

  BaseQuery(Connection this.conn);
}

class TestQuery extends BaseQuery {
  TestQuery(Connection conn) : super(conn); // type '_Future' is not a subtype of type 'Connection' of 'conn' where

  run() async {
    var results =  await conn.query("select 1").toList();

    // Do some data manipulation

    return results;
  }
}

class TestController {
  TestQuery testQuery;

  TestController(TestQuery this.testQuery);

  index() async {
    var results = await testQuery.run();

    var html = "<pre>" + results.toString() + "</pre>";

    return html;
  }
}

1 个答案:

答案 0 :(得分:0)

我可以重现但是当我将线路改为

<style>
.mstrmojo-DocSelector td {
    border-bottom-color: rgb(214, 214, 214);
    border-bottom-style: solid;
    border-right-style: solid;
    border-right-color: rgb(214, 214, 214);
    border-right-width: 0.111111em;
    border-bottom-width: 0.111111em
}

.mstrmojo-DocSelector td div {
    height: .24in;
}
</style>

它工作正常。

我认为你的代码应该也能正常工作。