Как я могу передать значения конструктору класса с помощью inversifyJS?
Здравствуйте, у вас есть тестовый проект для машинописи с inversify и requirejs, который можно клонировать с: https://github.com/ahedreville/ioctest.git
Его package.json является следующим
{
"name": "ioctest",
"version": "1.0.0",
"description": "Test of an IoC with Inversify and RequireJS",
"scripts": {
"start": "http-server"
},
"author": "Alexandre Hedreville",
"license": "ISC",
"devDependencies": {
"http-server": "^0.10.0"
},
"dependencies": {
"@types/requirejs": "^2.1.30",
"inversify": "^4.3.0",
"reflect-metadata": "^0.1.10",
"requirejs": "^2.3.4"
}
}
Вы можете запустить этот проект в своем браузере, выполнив следующие команды...
mkdir temp
cd temp
git clone https://github.com/ahedreville/ioctest.git
cd ioctest
c:\temp\ioctest>tree /F /A
...
C:.
| app.main.js
| index.html
| package.json
| README.md
| tsconfig.json
|
\---src
App.js
App.js.map
App.ts
ioc_config.js
ioc_config.js.map
ioc_config.ts
Question.js
Question.js.map
Question.ts
Question2.js
Question2.js.map
Question2.ts
Types.js
Types.js.map
Types.ts
npm install
npm start
http://localhost:8080
Как вы можете видеть, открывая журнал консоли разработчика браузера, интерфейс IProblem преобразуется в класс Question2, как мы и просили сделать для класса ioc_config.ts.
Вопрос2 класс выглядит следующим образом
import { injectable } from "inversify";
import { IProblem } from './Types';
@injectable()
export class Question2 implements IProblem {
public readonly factor: number = 0;
public count: number = 0;
public answer: number = 0;
}
но если я изменю целевой класс разрешения на ioc_config.ts
изменение класса ioc_config.ts следующим образом
import { Container } from 'inversify';
import { sTypes, IProblem } from './Types';
import { Question } from './Question';
import { Question2 } from './Question2';
export const container = new Container();
//container.bind<IProblem>(sTypes.IProblem).to(Question2);
container.bind<IProblem>(sTypes.IProblem).to(Question);
Теперь разрешение интерфейса IProblem не будет выполнено, так как Question.ts ИМЕЕТ КОНСТРУКТОР, КОТОРЫЙ ОЖИДАЕТ НЕКОТОРЫЕ ЗНАЧЕНИЯ для передачи.
Вопрос класс выглядит следующим образом
import { injectable } from "inversify";
import { IProblem } from './Types';
@injectable()
export class Question implements IProblem {
public answer: number = 0;
constructor(public readonly factor: number, public readonly count: number) {
}
}
Как я могу решить эту проблему (я новичок в Inversify) и передать некоторые значения во время разрешения конструктору?
заранее спасибо
1 ответ
Я думаю, что вам нужна фабрика:
interface Problem {
factor: number;
count: number;
}
interface ProblemFactory extends Function {
(factor: number, count: number): Problem;
}
class Question implements Problem {
public answer = 0;
constructor(public readonly factor: number, public readonly count: number) {
}
}
interface QuestionConstructor {
new(factor: number, count: number): Question;
}
container.bind<QuestionConstructor>("QuestionConstructor").toConstructor(Question);
container.bind<ProblemFactory>("ProblemFactory").toFactory<Problem>((context) => {
return (factor: number, count: number) => {
const Constructor = context.container.get<QuestionConstructor>("QuestionConstructor");
return new Constructor(factor, count);
};
});