如何注入一个asynchronous依赖inversify?

我有TypeScript应用程序,我正在使用Inversify for IoC。

我有一个连接类:

'use strict'; import { injectable } from 'inversify'; import { createConnection, Connection } from "typeorm"; import { Photo, PhotoMetadata, Author, Album } from '../index'; @injectable() class DBConnectionManager { public createPGConnection(): Promise<Connection> { return createConnection({ driver: { type: "postgres", host: "host", port: 5432, username: "username", password: "password", database: "username" }, entities: [ Photo, PhotoMetadata, Author, Album ], autoSchemaSync: true, }); } } export { DBConnectionManager }; 

在创build我的连接之后,我想将一个连接绑定到我的容器中:

 kernel.bind<Connection>('DefaultConnection').toConstantValue(getConnectionManager().get()); 

然后我想把它注入另一个类:

 import { injectable, inject } from 'inversify'; import { Connection, FindOptions } from "typeorm"; import { IGenericRepository, ObjectType } from '../index'; @injectable() class GenericRepository<T> implements IGenericRepository<T> { private connection: Connection; private type: ObjectType<T>; constructor( @inject('DefaultConnection') connection: Connection) { this.connection = connection; } 

所以在我的容器configuration如何绑定DefaultConnection,需要等待CreateConnection我可以做asynchronous和等待,但我不知道是否有一个更干净的方法来实现这inversify

       

网上收集的解决方案 "如何注入一个asynchronous依赖inversify?"

Inversify 2.0包括对asynchronous工厂(AKA Providers)的支持,

提供者允许你声明一个提供者如下:

 container.bind<<DbClient>("DbClient").to(DbClientClass); container.bind<interfaces.Provider<DbClient>>("Provider<DbClient>") .toProvider<DbClient>((context) => { return () => { return new Promise<DbClient>((resolve, reject) => { // Create instance let dbClient = context.container.get<DbClient>("DbClient"); // Open DB connection dbClient.initialize("//connection_string") .then(() => { resolve(dbClient); }) .catch((e: Error) => { reject(e); }); }); }; }); 

然后你可以注入并使用提供者。 唯一的问题是它需要两步初始化: constructor注入和async init()方法。

 class UserRepository { private _db: DbClient; private _dbProvider: Provider<DbClient>; // STEP 1 public constructor( @inject("Provider<DbClient>") provider: Provider<DbClient> ) { this._dbProvider = provider; } // STEP 2 private async init() { if (this._db) return this._db; this._db = await this._dbProvider(); return Promise.resolve(this._db); } public async getUser(): Promise<Users[]>{ let db = await this.init(); return db.collections.user.get({}); } public async deletetUser(id: number): Promise<boolean>{ let db = await this.init(); return db.collections.user.delete({ id: id }); } } 

我们正在研究一个新function来简化asynchronous值的注入。 这个特性将被包含在inversify 3.0中:

 class UserRepository { // STEP 1 public constructor( @inject("Provider<DbClient>") private provider: Provider<DbClient> ) {} public async getUser(): Promise<Users[]>{ // STEP 2: (No initialization method is required) let db = await this.provider.someFancyNameForProvideValue; return db.collections.user.get({}); } } 

只需在应用程序启动时创build连接并绑定已连接的实例,通常您并不需要推迟连接。