gpt4 book ai didi

node.js - 如何在 inversify 中注入(inject)异步依赖?

转载 作者:搜寻专家 更新时间:2023-10-30 20:37:04 30 4
gpt4 key购买 nike

我有 TypeScript 应用程序,我正在使用 Inversify对于 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 };

创建连接后,我想将一个连接绑定(bind)到我的容器中:

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

然后我想将它注入(inject)到另一个类中:

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;
}

所以在我的容器配置中,如何绑定(bind)需要等待 CreateConnection 的 DefaultConnection我可以使用异步并等待,但我想知道在 inversify 中是否有更简洁的方法来实现此目的

最佳答案

Inversify 2.0 包括对异步工厂(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);
});
});
};
});

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

class UserRepository { 

private _db: DbClient;
private _dbProvider: Provider<DbClient>;

// STEP 1
// Inject a provider of DbClient to the constructor
public constructor(
@inject("Provider<DbClient>") provider: Provider<DbClient>
) {
this._dbProvider = provider;
}

// STEP 2
// Get a DB instance using a provider
// Returns a cached DB instance if it has already been created
private async getDb() {
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.getDb();
return db.collections.user.get({});
}

public async deletetUser(id: number): Promise<boolean>{
let db = await this.getDb();
return db.collections.user.delete({ id: id });
}

}

我们正在研究 new feature以简化异步值的注入(inject)。此功能将包含在 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({});
}
}

关于node.js - 如何在 inversify 中注入(inject)异步依赖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40880447/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com