反转合成根以进行构造函数注入

时间:2018-10-09 04:27:08

标签: angular typescript inversifyjs

我来自c#背景。我是Angular 6的新手。我了解到存在类似于ninject for DI的lib。变聪明。我试图在应用程序中使用它。

我确实配置了绑定和类型。

TYPES.ts

const TYPES = {
    IAppService : Symbol.for("IAppService")
};

export {TYPES}

Bindings.ts

import 'reflect-metadata';
import { Container } from "inversify"
import { TYPES } from "./TYPES"
import { IAppService } from "./services/IAppService"
import { AppService } from "./services/AppService"


const inversifyContainer = new Container();
inversifyContainer.bind<IAppService>(TYPES.IAppService).to(AppService).inSingletonScope();

export { inversifyContainer };

我正在注入APPService的班级

    import { inject } from "inversify";
    import { Component, OnInit } from '@angular/core';
    import { AppModel } from './model/AppModel'
    import { IAppService } from './services/IAppService';
    import { TYPES } from "./TYPES";


    @Component({
        selector: 'summary-app',
        templateUrl: './summary-app.component.html'
    })
    export class SummaryApp implements OnInit {

        private _service: IAppService;

        constructor(
            @inject(TYPES.IAppService) service: IAppService,
        ) {
            this._service = service;
        }
}

Module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppService } from "./services/AppService"
import { SummaryApp } from './summary-app.component';

@NgModule({
  declarations: [
    SummaryApp
  ],
  imports: [
    BrowserModule
  ],
  providers: [
    AppService
  ],
  bootstrap: [SummaryApp]
})
export class AppModule {
}

编译成功。 但出现运行时错误无法解析SummaryApp的所有参数

这意味着inverseify无法解决依赖性。 我看到了许多使用服务定位器解决依赖关系的示例。但是我感觉到它的反模式。在哪里可以有成分根来反转容器?

1 个答案:

答案 0 :(得分:0)

SummaryApp 是否通过容器实例化?如果情况并非如此,我们就不是最好的情况。我看到了两种不同的解决方案:

  1. 尝试通过 inversify 容器实例化 SummaryApp(我不是 Angular 专家,所以我不知道如何完成这样的壮举)
  2. 使用@lazyInject
import getDecorators from "inversify-inject-decorators";

import { container } from 'your-container-module';

const { lazyInject } = getDecorators(container); // Export your inversify container

@Component({
    selector: 'summary-app',
    templateUrl: './summary-app.component.html'
})
export class SummaryApp implements OnInit {

    private _service: IAppService;

    constructor(
        @lazyInject(TYPES.IAppService) service: IAppService,
    ) {
        this._service = service;
    }
}


此装饰器使用代理来执行对 inversify 容器的调用。除非您的打包程序在 inversify 放置代理后重新定义该属性(请参阅 this issue 了解更多详情)