Node.js 如何在inversify中注入异步依赖项?
我有一个TypeScript应用程序,我正在为IoC使用 我有一个连接类:Node.js 如何在inversify中注入异步依赖项?,node.js,typescript,inversion-of-control,inversifyjs,typeorm,Node.js,Typescript,Inversion Of Control,Inversifyjs,Typeorm,我有一个TypeScript应用程序,我正在为IoC使用 我有一个连接类: 'use strict'; import { injectable } from 'inversify'; import { createConnection, Connection } from "typeorm"; import { Photo, PhotoMetadata, Author, Album } from '../index'; @injectable() class DBConnectionManag
'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 };
“严格使用”;
从'inversify'导入{可注射的};
从“typeorm”导入{createConnection,Connection};
从“../index”导入{Photo,PhotoMetadata,Author,Album};
@可注射()
类DBConnectionManager{
公共createPGConnection():承诺{
返回createConnection({
司机:{
类型:“博士后”,
主持人:“主持人”,
港口:5432,
用户名:“用户名”,
密码:“密码”,
数据库:“用户名”
},
实体:[
照片、影像数据、作者、相册
],
AutoSchemaAsync:true,
});
}
}
导出{DBConnectionManager};
创建连接后,我希望将连接绑定到容器中:
kernel.bind<Connection>('DefaultConnection').toConstantValue(getConnectionManager().get());
kernel.bind('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;
}
import{injectable,injecte}来自'inversify';
从“typeorm”导入{Connection,FindOptions};
从“../index”导入{IGenericRepository,ObjectType};
@可注射()
类GenericRepository实现IGenericRepository{
私人连接:连接;
私有类型:ObjectType;
构造函数(@inject('DefaultConnection')连接:连接){
这个连接=连接;
}
因此,在容器配置中,如何绑定需要等待CreateConnection的DefaultConnection
我可以使用async和wait,但我想知道是否有更干净的方法来实现这一点,Inversify 2.0包括对异步工厂的支持(也称为提供程序) 提供程序允许您按如下方式声明提供程序:
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);
});
});
};
});
我们正在开发一种简化异步值注入的方法。此功能将包含在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({});
}
}
class用户存储库{
//第一步
公共构造函数(
@注入(“提供者”)私有提供者:提供者
) {}
公共异步getUser():承诺{
//步骤2:(不需要初始化方法)
让db=wait this.provider.someFancyNameForProvideValue;
返回db.collections.user.get({});
}
}
只需在应用程序启动时创建连接并绑定已连接的实例,通常不需要延迟连接。如果应用程序连续运行,并且假设所有初始化/依赖关系构建都在第一个请求到来之前完成,则这将行得通。如果您尝试解除连接对于无服务器框架,您的应用程序在收到请求之前不会初始化。这意味着您将遇到计时/竞争条件。在我的情况下,IoC容器尚未完成设置,因此应用程序会遇到运行时错误,因为在处理请求时正在生成依赖项。
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({});
}
}