I am looking into improving my overall application architecture and (I think) I understand the issues my Anemic Models are causing.
Here is my current architecture:
- Controller with injected Service and Controller Action accepting a DTO
- Service with injected repository. Service function takes DTO, calls repository, does whatever it needs to do with the entity (lets say update properties on the entity) and saves it.
What's wrong with above:
In this setup, all Entity properties have Public getters and setters, there is no encapsulation, no OOP, no code re-usability. When I need to update this entity in another Service (or any other method for that matter), I have to write the same code again.
How to fix this:
Obviously this is not ideal. I've decided it would make sense to make the Entity Rich, by adding an Update method to allow me to reuse my code throughout all my services.
Confusion:
Where I am confused is,
- How does my Rich Entity communicate with the Service?
- Should my Update method in the Entity take the IEntityRepository as parameter so I can call repository.Save() in the Entity?
- Should repository.Save() be called in the Service?
- What if I need to call an Http API from the service because of some specific action happening in the Update in the Entity? Should I call the Http API from the Entity Update() method?
Thanks tons for any directions on how to deal with this.
user.email = '[email protected]'
, thenuserRepository.save(user)
.email
I might have to call one of my microservices to do an update. Or trigger a background job. Or wipe my redis cache. Or update some other entities etc. etc.email
is changed, I would expect theuserRepository
to be responsible for setting that process in motion. Because that's when the change is actually happening.