Skip to content
On this page

IOC介绍 ​

Controller ​

就是对不同的请求,相应的调用不同的Service的具体实现。

Service ​

负责具体的业务逻辑,调用Repository 来做增删改查。

Repository ​

数据库的增删改查操作,封装了数据源,依赖DataSource连接数据库。

DataSource ​

连接数据库,依赖Config拿到账号密码等信息。

Config ​

配置文件,用来配置数据库账号密码等信息。

问题 ​

Controller 依赖了 Service 实现业务逻辑,Service 依赖了 Repository 来做增删改查,Repository 依赖 DataSource 来建立连接,DataSource 又需要从 Config 对象拿到用户名密码等信息。

js
const config = new Config({ username: 'xxx', password: 'xxx'});

const dataSource = new DataSource(config);

const repository = new Repository(dataSource);

const service = new Service(repository);

const controller = new Controller(service);

我们需要手动构造对象,并将依赖传入,十分麻烦

IOC怎么解决 ​

之前我们手动创建和组装对象不是很麻烦么,我能不能在 class 上声明依赖了啥,然后让工具去分析我声明的依赖关系,根据先后顺序自动把对象创建好了,然后组装起来呢?

它有一个放对象的容器,程序初始化的时候会扫描 class 上声明的依赖关系,然后把这些 class 都给 new 一个实例放到容器里。 创建对象的时候,还会把它们依赖的对象注入进去。

具体 ​

  1. 定义类时,使用 @inject @Controller装饰器声明
  2. 将Provider和Container类,放入@Module的类装饰器中
  3. 在构造函数参数上直接声明依赖(属性注入也行)
  4. nest会帮我们将我们声明的依赖注入到构造函数中