【发布时间】:2019-03-28 20:54:57
【问题描述】:
我正在通过尝试实现一个干净的架构结构来试验 Nestjs,我想验证我的解决方案,因为我不确定我是否理解最好的方法。 请注意,该示例几乎是伪代码,并且很多类型都缺失或泛型,因为它们不是讨论的重点。
从我的领域逻辑开始,我可能想在如下类中实现它:
@Injectable()
export class ProfileDomainEntity {
async addAge(profileId: string, age: number): Promise<void> {
const profile = await this.profilesRepository.getOne(profileId)
profile.age = age
await this.profilesRepository.updateOne(profileId, profile)
}
}
这里我需要访问profileRepository,但是遵循干净架构的原则,我不想为刚才的实现而烦恼,所以我为它写了一个接口:
interface IProfilesRepository {
getOne (profileId: string): object
updateOne (profileId: string, profile: object): bool
}
然后我在 ProfileDomainEntity 构造函数中注入依赖项,并确保它遵循预期的接口:
export class ProfileDomainEntity {
constructor(
private readonly profilesRepository: IProfilesRepository
){}
async addAge(profileId: string, age: number): Promise<void> {
const profile = await this.profilesRepository.getOne(profileId)
profile.age = age
await this.profilesRepository.updateOne(profileId, profile)
}
}
然后我创建了一个简单的内存实现,让我运行代码:
class ProfilesRepository implements IProfileRepository {
private profiles = {}
getOne(profileId: string) {
return Promise.resolve(this.profiles[profileId])
}
updateOne(profileId: string, profile: object) {
this.profiles[profileId] = profile
return Promise.resolve(true)
}
}
现在是时候使用模块将所有东西连接在一起了:
@Module({
providers: [
ProfileDomainEntity,
ProfilesRepository
]
})
export class ProfilesModule {}
这里的问题是 ProfileRepository 显然实现了 IProfilesRepository 但它不是 IProfilesRepository 因此,据我了解,令牌不同,Nest 无法解决依赖关系。
我发现的唯一解决方案是使用自定义提供程序来手动设置令牌:
@Module({
providers: [
ProfileDomainEntity,
{
provide: 'IProfilesRepository',
useClass: ProfilesRepository
}
]
})
export class ProfilesModule {}
并通过指定要与@Inject 一起使用的令牌来修改ProfileDomainEntity:
export class ProfileDomainEntity {
constructor(
@Inject('IProfilesRepository') private readonly profilesRepository: IProfilesRepository
){}
}
这是处理我所有依赖项的合理方法还是我完全偏离了轨道? 有没有更好的解决方案? 我对所有这些东西都很陌生(NestJs、干净的架构/DDD 和 Typescript),所以我在这里可能完全错了。
谢谢
【问题讨论】:
-
使用抽象类(+无默认功能)而不是接口(+字符串提供者)有什么好处?或相反。
标签: typescript dependency-injection domain-driven-design nestjs clean-architecture