一个东西(Object)需要其它东西提供的功能,就把这些提供功能的东西附加到需要它们的东西里面,这就是依赖注入。从字面意思去理解,不用考虑的太复杂了。依赖注入,就是注入需要的依赖的东西。
看个例子,有个类叫 ImageController,它里面的 index 方法可以返回所有的图像资源,在这个方法里依赖 ImageService 里面提供的服务,它会帮 ImageController 的 index 方法找到需要的图像资源。
不使用依赖注入
ImageController 需要 ImageService 里的功能,如果不使用依赖注入的方式,代码大概像这样:
class ImageService {
private readonly images = [];
findAll() {
return this.images;
}
}
class ImagesController {
private imageService;
constructor() {
this.imageService = new ImageService();
}
index() {
return this.imageService.findAll();
}
}在上面的例子里面没有使用依赖注入,而是直接在类的构造方法里自己创建了一个 ImageService 实例。这个 ImageService 就是 ImagesController 里依赖的一个东西,因为在它的 index 方法里,需要使用 ImageService 里的 findAll() 方法获取到需要的图像资源。
使用依赖注入
使用依赖注入会让代码更灵活一些。下面用依赖注入的方式改造一下 ImageController 这个类:
class ImagesController {
constructor(private imageService: ImageService) {}
index() {
return this.imageService.findAll();
}
}用的时候需要这样:
const imageService = new ImageService(); const imagesController = new imagesController(imageService)




评论
皓哥,讲一讲 IoC 控制反转?
6 年 7 个月 以前
行啊,可以再多解释一下 :)
6 年 7 个月 以前