随着业务需求的逐渐增多,controller模块下业务代码越写越多,代码显得很臃肿,不易管理,很明显,传统的MVC分层架构已经不能满足业务的需求。这个时候就需要抽离出一个service层来对controller中业务模块进行抽离,而controller则负责处理请求的输入、输出以及根据需求要求调用相应的service模块处理。
Injectable
service同样是支持IOC的,Injectable是keverjs内置的IOC装饰器,它的作用是标记被装饰的模块是可被注入的。使用方式如下:
ts
import { Injectable } from '@kever/ioc'
@Injectable('user')
export class UserService {
async getUser(id: number) {
return {
id,
name: 'keverjs'
}
}
}Injectable装饰器需要传入Tag,可以是string或者symbol类型,用于标记可被注入类。
Inject
当一个service被标记为可被注入后,在controller中就可以使用Inject装饰器,将可被注入service注入到controller中.使用方式如下:
ts
import { Controller, Context } from '@kever/core'
import { Inject } from '@kever/ioc'
import { Get } from '@kever/router'
import { UserService } from '../service/UserService.ts' //将类型引入过来,保证类型的准确性
@Controller('/')
export class UserController {
@Inject('user')
public userService: UserService
@Get('/user')
async getUser(ctx: Context) {
const user = this.userService.getUser(1)
ctx.body = user
}
}Inject装饰器在使用使也需要传入Tag,与Injectable类型一致,用来注入被Injectable标记的service。