我试图了解我应该如何在项目中实现组合根。
根据我的红色,如果以错误的方式使用组合根(例如,通过在应用程序代码的很多地方引用它),您最终会得到服务定位器。
让我向您展示一个没有组合根的项目示例。
我有以下项目结构:
- 服务器.ts
- 域.ts
- 应用程序.ts
- api.ts
- sql 存储库
服务器.ts:
此文件导入 API 并初始化服务器。
import express from 'express';
import API from './api'
const app = express();
const port = 3000;
app.use(express.json());
app.use(API);
// Start server
app.listen(port, () => {
console.log('listening on port: ' + port);
});
域.ts:
该文件包含域的核心逻辑。
export type Entity = {
param1: string,
param2: string,
};
export type IRepository = {
GetMultipleEntities(filterParam: string): Entity[] | undefined
GetEntity(filterParam: string): Entity | undefined
CreateEntity(entity: Entity): void
UpdateEntity(entity: Entity): void
}
应用程序.ts:
该文件包含应用程序的用例。
import {IRepository} from './domain';
export const CheckIfEntityExists = (filterParam: string, entityRepository: IRepository): boolean => {
let entity = entityRepository.GetEntity(filterParam);
return typeof entity != "undefined";
};
sql-repository.ts:
该文件包含 IRepository 接口的具体实现
import {Entity, IRepository} from './domain';
export class SqlRepository implements IRepository {
GetEntity(filterParam: string): Entity {
//
// some sort of logic to get entity from an sql database
//
return {
param1: '',
param2: ''
};
}
GetMultipleEntities(filterParam: string): Entity[] {
//
// some sort of logic to get multiple entity from an sql database
//
return [
{
param1: '',
param2: ''
},
{
param1: '',
param2: ''
}
];
}
CreateEntity(entity: Entity): void {
// some logic to enter new data to the sql database that represents an entity
}
UpdateEntity(entity: Entity): void {
// some logic to update the entity
}
}
api.ts:
此文件包含使用 application.ts 文件中的用例的 api
import {Router} from 'express'
import {CheckIfEntityExists} from './application';
import {SqlRepository} from './sql-repository';
const router = Router();
router.get("/exists/:filterParam", async (req, res) => {
CheckIfEntityExists(req.params.filterParam, new SqlRepository);
res.end()
});
export default router
Ofc 这只是一个示例,但您了解项目的外观。
从您所见,一切都很好,直到我们看到 api.ts 文件。它导入具体实现并将其注入到用例中。如果要导入和使用更多的依赖项怎么办,我不希望 api.ts 负责决定哪些实现去哪个地方,这不是它的责任。
但另一方面,我应该如何实现组合根呢?我不知道我应该如何构造完整的对象图,然后将其传递给服务器对象,以便正确的实现将转到正确的对象。
提前致谢!