我有 TypeScript 应用程序,并且正在为 IoC 使用Inversify。
我有一个连接类:
'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 };
创建连接后,我想将连接绑定到我的容器中:
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;
}
因此,在我的容器配置中,如何绑定需要等待 CreateConnection 的 DefaultConnection 我可以使用 async 并等待,但我想知道是否有一种更简洁的方法可以在inversify中实现这一点