如何在打字稿中使用依赖注入?

我试图在类型脚本代码中添加依赖项注入功能,但是我需要在依赖项注入中加载快速应用程序。

Dependencies.ts

import { injectable } from 'inversify';

@injectable()
export class DependencyA{
    public getName(){
        return "dependencyA"
    }
}

@injectable()
export class DependencyB{
    public getName(){
        return "dependencyB"
    }
}

Service.ts

import {injectable} from 'inversify';
import { DependencyA,DependencyB } from './dependencies';

@injectable()
export class Service{
    dependencya: DependencyA;
    dependencyb: DependencyB;
    constructor(dependencya:DependencyA,dependencyb:DependencyB){
        this.dependencya = dependencya;
        this.dependencyb = dependencyb

    }

    public getallName(){
        return this.dependencya
    }
}

main.ts

import 'reflect-metadata'
import { Service } from './service';
import {container} from 'tsyringe';

const service = container.resolve(Service)  
console.log(service.getallName)

如何在依赖项注入中加载Express应用程序,以及Express App在依赖项构造函数中传递参数

a2207210 回答:如何在打字稿中使用依赖注入?

我将确保您坚持在整个应用程序中使用Inverseify,并使用Inverseify的Container而不是tsyringe中的容器。

我还将向您介绍此软件包(https://github.com/inversify/inversify-express-utils),我已在生产中成功使用该软件包(使用DI进行基于服务的快速应用程序)。

您可以创建一个InversifyExpressServer,像这样将其传递给您的容器和自定义快递应用

const container = new Container();

container.bind<MyServiceA>(TYPES.MyServiceA).to(MyServiceA)
container.bind<MyServiceB>(TYPES.MyServiceB).to(MyServiceB)

const app = express();

// apply middleware
app.use(middleware)

// any regular functional express routes
app.use('/',controllerFunc)

...etc etc

const server = new InversifyExpressServer(container,null,app);

InversifyExpressServer将为您解决ioc根并注册所有控制器,您要做的就是将服务绑定到容器。然后,@inject将可以使用这些服务,并在您的控制器(或其他服务)中使用这些服务

@controller("/names")
export class NamesController extends HttpBaseController {
    @inject(TYPES.MyServiceA) private myServiceA!: MyServiceA

    @httpGet("/")
    private index(): string {
        return this.myServiceA.getAllNames();
    }
}

它与现有应用程序很好地集成在一起。我当前正在使用此inversify包将具有〜100个端点的Express应用程序从纯js Express应用程序迁移到ts应用程序。由于您可以通过InversifyExpressServier一个自定义应用程序,因此可以在其中保留所有旧路由的所有功能,直到对其进行重构为止。

或者,如果您的项目是新项目,建议您检举Nestjs(https://nestjs.com/)。这是一个在express上构建的框架,它自己是在angular的启发下内置的依赖反转。

本文链接:https://www.f2er.com/3068419.html

大家都在问