I m studying DDD these days, and I m having some questions concerning how to manage repositories with DDD.
Actually, I have met two possibilies :
First one
The first way of manage services I've read is to inject a repository and a domain model in an application service.
This way, in one of the application service methods, we call a domain service method (checking business rules) and if the condition is good, the repository is called on a special method to persist / retrieve the entity from the database.
A simple way of doing this could be :
class ApplicationService{
constructor(domainService, repository){
this.domainService = domainService
this.repository = repository
}
postAction(data){
if(this.domainService.validateRules(data)){
this.repository.persist(new Entity(data.name, data.surname))
}
// ...
}
}
Second one
The second possibility is to inject the repository inside of the domainService instead, and to only use the repository through the domain service :
class ApplicationService{
constructor(domainService){
this.domainService = domainService
}
postAction(data){
if(this.domainService.persist(data)){
console.log('all is good')
}
// ...
}
}
class DomainService{
constructor(repository){
this.repository = repository
}
persist(data){
if(this.validateRules(data)){
this.repository.save(new Entity(data.name))
}
}
validateRules(data){
// returns a rule matching
}
}
From now, I m not able to distinguish which one is the best (if there's one best) or what they imply both in their context.
Can you provide me example where one could be better than the other and why ?