Inversify 实例未正确注入
Inversify instance is not injected properly
我在 hapijs v20 和 typescript 中使用 inversify。
当我尝试在 class 中绑定一个依赖项来处理这样的请求时:
import * as Hapi from '@hapi/hapi'
import { injectable, inject } from "inversify";
import { types } from "../types";
@injectable()
export default class SomeController implements SomeInterface {
private dep: any
public constructor(@inject(types.SomeDependecy) dep: SomeDependecy) {
this.dep = dep
}
public validate(request: Hapi.Request, reply: Hapi.ResponseToolkit): Hapi.ResponseObject {
const result = this.dep.validate(request) // The headache line
return reply.response(result)
}
}
然后注入使用这个 class 来注册这样的路由:
public constructor(@inject(types.SomeController) controller: SomeController) {
this.controller = controller
}
public async register(server: Server) {
await server.route([
{
method: 'POST',
path: '/validate',
handler: this.controller.validate
}
])
}
一切正常,实例似乎已创建。然而,当我到达终点时,我得到:
TypeError: Cannot read property 'dep' of undefined
从控制器中注释为头痛的行中抛出:C
你们知道是什么原因造成的吗?
经过一番研究,我找到了这个问题的答案:
Hapi showing undefined variable inside handler
并将注册更改为:
await server.route([
{
method: 'POST',
path: '/validate',
handler: (request, reply) => {
return this.controller.validate(request, reply)
}
}
])
我在 hapijs v20 和 typescript 中使用 inversify。
当我尝试在 class 中绑定一个依赖项来处理这样的请求时:
import * as Hapi from '@hapi/hapi'
import { injectable, inject } from "inversify";
import { types } from "../types";
@injectable()
export default class SomeController implements SomeInterface {
private dep: any
public constructor(@inject(types.SomeDependecy) dep: SomeDependecy) {
this.dep = dep
}
public validate(request: Hapi.Request, reply: Hapi.ResponseToolkit): Hapi.ResponseObject {
const result = this.dep.validate(request) // The headache line
return reply.response(result)
}
}
然后注入使用这个 class 来注册这样的路由:
public constructor(@inject(types.SomeController) controller: SomeController) {
this.controller = controller
}
public async register(server: Server) {
await server.route([
{
method: 'POST',
path: '/validate',
handler: this.controller.validate
}
])
}
一切正常,实例似乎已创建。然而,当我到达终点时,我得到:
TypeError: Cannot read property 'dep' of undefined
从控制器中注释为头痛的行中抛出:C
你们知道是什么原因造成的吗?
经过一番研究,我找到了这个问题的答案:
Hapi showing undefined variable inside handler
并将注册更改为:
await server.route([
{
method: 'POST',
path: '/validate',
handler: (request, reply) => {
return this.controller.validate(request, reply)
}
}
])