如何在inverseify中注入异步依赖项? [英] How to inject an asynchronous dependency in inversify?

查看:109
本文介绍了如何在inverseify中注入异步依赖项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有TypeScript应用程序,并且正在为IoC使用 Inversify .

I have TypeScript application and I'm using 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 };

创建连接后,我想将连接绑定到我的容器中

After I created my connection I want to bind a connection into my container:

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

然后我想将其注入另一个类:

and then I want to inject it into another class:

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 我可以进行异步处理并等待,但是我想知道 inversify

So in my container configuration how can I bind DefaultConnection that needs to wait for CreateConnection I can do with async and wait but I'm wonder if there is a cleaner way to achive this in inversify

推荐答案

Inverseify 2.0包括对异步工厂(AKA提供程序)的支持

Inversify 2.0 includes support for asynchronous factories (AKA Providers)

提供程序允许您按以下方式声明提供程序:

A provider allows you can to declare a provider as follows:

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 getDb()方法.

Then you can inject and consume the provider. The only problem is that it requires two-step initialization: the constructor injection and the async getDb() method.

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

}

我们正在开发新功能,以简化异步值的注入.此功能将包含在Inverseify 3.0中:

We are working on a new feature to simplify the injection of asynchronous values. This feature will be included in 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({});
    }
}

这篇关于如何在inverseify中注入异步依赖项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆