I have a common scenario that I am looking for some recommendations from people more experienced with DDD and Domain Modeling in general.
Let's say I'm starting to build a blog mechanism, and the first requirement is that after publishing an article, users can start posting comments on it. This starts fine and leads to the following design:
public class Article { public int Id { get; set; } public void AddComment(Comment comment) {
My MVC controller is designed as follows:
public class ArticleController { private readonly IRepository _repository; public ArticleController(IRepository repository) { _repository = repository; } public void AddComment(int articleId, Comment comment) { var article = _repository.Get<Article>(articleId); article.AddComment(comment); _repository.Save(article); return RedirectToAction("Index"); } }
Now everything works fine, and it meets the requirement. In the next iteration, we get the requirement that every time a Comment is sent, the blog author must receive an email notification.
At the moment, I have two options that I can think of. 1) Modify the article to require IEmailService (in ctor?) Or get EmailService from a static link to my DI container
1a) It seems pretty ugly. I believe this violates some domain model rules that my entities know about services?
public class Article { private readonly IEmailService _emailService; public Article(IEmailService emailService) { _emailService = emailService; } public void AddComment(Comment comment) {
1b) Also seems ugly, now I require a configured DI container that is accessed statically.
public class Article { public void AddComment(Comment comment) {
2) Create the IArticleService service and move the AddComment () method to this service, and not to the article object itself.
This solution is cleaner, I believe, but adding a comment is now less searchable and requires ArticleService to do the job. It seems that AddComment should belong to the Article class itself.
public class ArticleService { private readonly IEmailService _emailService; public ArticleService(IEmailService emailService) { _emailService = emailService; } public void AddComment(Article article, Comment comment) {
Therefore, I mainly seek advice from people more experienced in domain modeling. If I don't have a more obvious solution, let me know :)
I donβt like both solutions, to be honest, because the Service option is less clear. I can no longer add a comment to an article instance without an accessible article. It also seems less natural, as AddComment seems such an obvious method for the type of article.
In any case, I look forward to reading the input. Thanks in advance.