- Architecting Angular Applications with Redux,RxJS,and NgRx
- Christoffer Noring
- 364字
- 2021-08-27 19:56:15
Service with dependencies
A service with dependencies has dependencies in the constructor that we need help resolving. Without this resolution process, we can't create the service. Such a service may look like this:
export class Service {
constructor(
Logger logger: Logger,
repository:Repository
) {}
}
In this code, our service has two dependencies. Upon constructing a service, we need one Logger instance and one Repository instance. It would be entirely possible for us to find the Logger instance and Repository instance by typing something like this:
import { Service } from './service'
import logger from './logger';
import { Repository } from './repository';
// create the service
let service = new Service( logger, new Repository() )
This is absolutely possible to do. However, the code is a bit tedious to write every time I want a service instance. When you start to have 100s of classes with deep object dependencies, a DI system quickly pays off.
This is one thing a Dependency Injection library helps you with, even if it is not the main motivator behind its existence. The main motivator for a DI system is to create loose coupling between different parts of the system and rely on contracts rather than concrete implementations. Take our example with the service. There are two things a DI can help us with:
- Switch out one concrete implementation for another
- Easily test our construct
To show what I mean, let's first assume Logger and Repository are interfaces. Interfaces may be implemented differently by different concrete classes, like so:
import { Service } from './service'
import logger from './logger';
import { Repository } from './repository';
class FileLogger implements Logger {
log(message: string) {
// write to a file
}
}
class ConsoleLogger implements Logger {
log(message: string) {
console.log('message', message);
}
}
// create the service
let service = new Service( new FileLogger(), new Repository() )
This code shows how easy it is to switch out the implementation of Logger by just choosing FileLogger over ConsoleLogger or vice versa. The test case is also made a lot easier if you only rely on dependencies coming from the outside, so that everything can therefore be mocked.
- C++黑客編程揭秘與防范
- Truffle Quick Start Guide
- Microservice Patterns and Best Practices
- 基于性能的保障理論與方法
- 網(wǎng)管第一課:網(wǎng)絡(luò)操作系統(tǒng)與配置管理
- 網(wǎng)絡(luò)利他行為研究:積極心理學(xué)的視角
- 深入理解計(jì)算機(jī)網(wǎng)絡(luò)
- Hands-On Docker for Microservices with Python
- 圖解物聯(lián)網(wǎng)
- NB-IoT原理和優(yōu)化
- 智能物聯(lián)網(wǎng):區(qū)塊鏈與霧計(jì)算融合應(yīng)用詳解
- 結(jié)網(wǎng)@改變世界的互聯(lián)網(wǎng)產(chǎn)品經(jīng)理(修訂版)
- CCNP TSHOOT(642-832)學(xué)習(xí)指南
- 互聯(lián)網(wǎng)下一站:5G與AR/VR的融合
- 中小型局域網(wǎng)搭建與管理實(shí)訓(xùn)教程