我正在使用 Tsyringe 编写 CLI 并出现错误。我不确定我知道为什么。
Error: Attempted to construct an undefined constructor. Could mean a circular dependency problem. Try using `delay` function.
这是代码:
//--- loco
#!/usr/bin/env node
const process = require('process')
const Locomotion = require('../dist')
const ts = require('tsyringe')
async function main() {
//const loco = new Locomotion.Locomotion()
//console.log(ts.container)
const client = ts.container.resolve(Locomotion)
await client.init()
await client.start()
}
main()
.then(() => {
process.exit(0)
})
.catch((err) => {
console.error(err) // Writes to stderr
process.exit(1)
})
//--- index.ts (called by loco)
import 'reflect-metadata'
import { container } from 'tsyringe'
import { Locomotion } from './Locomotion'
import { ConfigurationReader } from './ConfigurationReader'
container.register('ConfigurationReaderInterface', {
useClass: ConfigurationReader,
})
export { Locomotion }
//--- Locomotion.ts
import { inject, injectable } from 'tsyringe'
import { ConfigurationReaderInterface } from './interfaces/ConfigInterfaces'
@injectable()
export class Locomotion {
constructor(@inject('ConfigurationReaderInterface') private _reader: ConfigurationReaderInterface) {}
public async init() {
console.log('init')
}
public async start() {
console.log('start')
}
}
//--- ConfigurationReader.ts
import { ConfigurationInterface, ConfigurationReaderInterface } from './interfaces/ConfigInterfaces'
export class ConfigurationReader implements ConfigurationReaderInterface {
_config?: ConfigurationInterface | null
constructor() {
this._config = null
}
public async load() {}
}
//--- ConfigInterfaces.ts
type SuffixPairType = {
up: string
down: string
}
interface ConfigurationInterface {
name: string
aliases: Array<string>
migrationPath: string
suffixes: SuffixPairType
dialect: string
host: string
port: number
database: string
schema: string
user: string
password: string
}
interface ConfigurationReaderInterface {
load(): void
}
export { SuffixPairType, ConfigurationInterface, ConfigurationReaderInterface }