# 依赖注入

依赖注入(Dependency Injection)简称 DI, 它是实现控制反转(Inversion of Control – IoC)的一个模式, DI 的本质目的是为了解耦,保持组件之间的松散耦合,为设计开发带来灵活性。


# 类属性注入

使用 @Autowired 来注入依赖对象





 










import { Get, Controller, Autowired } from '@tiger/common';
import UserService from '../serv/user'

@Controller('/examples')
export class Example {

  @Autowired
  userService: UserService;

  @Get()
  index() {
    // this.userService.foo()
  }
}

# 类方法注入

类方法可以根据参数类型直接进行注入






 





import { Get, Controller } from '@tiger/common'
import UserService from '../service/user'

@Controller('/examples')
export class Example{
  @Get()
  index(userService: UserService) {
    // ...
  }
}

# 类构造函数注入

构造函数可以使用 ts 语法糖的方式注入




 









import { Get, Controller } from '@tiger/common'
import UserService from '../service/user'

@controller('/examples')
export class Example {
  constructor(private userService: UserService) {}

  @Get()
  index() {
    // ...
  }
}