Answer the question
In order to leave comments, you need to log in
How to write an adequate DI in TypeScript for a Nodejs application?
You need something like this:
startup.ts
export class AppConfiguration {
constructor() {
}
}
@CreatableModule({
services: [AppConfiguration]
})
export class StartupModule {
constructor(public appConfig: AppConfiguration) {
console.log(appConfig)
}
public f() {
console.log(this.appConfig)
}
}
export default class Injector {
private static registry: {[key: string]: any} = {};
static getRegistered(key: string): any {
var registered = Injector.registry[key];
if (registered) {
return registered;
} else {
throw new Error(`Error: ${key} was not registered.`);
}
}
static register(key: string, value: any) {
var registered = Injector.registry[key];
if (registered) {
throw new Error(`Error: ${key} is already registered.`);
}
Injector.registry[key] = value;
}
}
interface ICreatable<T> extends Function {
new (): T;
create: (...args) => T;
}
function CreatableModule(options) {
return function (target) {
options.services.forEach(service => {
Injector.register(service.constructor.name, service)
});
console.log(options)
console.log(target)
target.create = (...args) => new target(...args);
return target;
}
}
import {StartupModule} from "./app/Startup";
// правда не совсем понимаю как запускать в итоге этот модуль, чтобы он стартовал и у него уже были доступны внутри сервисы
new StartupModule();
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question