How to avoid anemic domain models, or when to move methods from the entities into services

前端 未结 5 1040
悲&欢浪女
悲&欢浪女 2021-01-29 22:19

I have a common scenario that I am looking for some guidance from people more experienced with DDD and Domain Modeling in general.

Say I start out building a blog engine

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-29 22:33

    Without using domain events, you can use the Double Dispatch pattern and put the AddComment logic inside a Domain Service.

    This is how it would look like:

    public class Article
    {
        public void AddComment(Comment comment, IAddCommentProcessor commentProcessor)
        {
            commentProcessor.AddComment(this, comment);
        }
    }
    
    public interface IAddCommentProcessor
    {
        void AddComment(Article article, Comment comment);
    }
    
    public class AddCommentAndEmailProcessor : IAddCommentProcessor
    {
        private readonly _emailService;
        public AddCommentAndEmailProcessor(EmailService emailService)
        {
            _emailService = emailService;
        }
    
        public void AddComment(Article article, Comment comment)
        {
            // Add Comment
    
            // Email
            _emailService.SendEmail(App.Config.AdminEmail, "New comment posted!");
        }
    }
    
    public class ArticleController
    {
        private readonly IRepository _repository;
        private readonly IArticleService _articleService;
    
        public ArticleController(IRepository repository, IArticleService articleService)
        {
            _repository = repository;
            _articleService = articleService;
        }
    
        public void AddComment(int articleId, Comment comment)
        {
            var article = _repository.Get
    (articleId); article.AddComment(comment, new AddCommentAndEmailProcessor(ServiceLocator.GetEmailService())); // Or you can use DI to get the Email Service, or any other means you'd prefer _repository.Save(article); return RedirectToAction("Index"); } }

    If you prefer, you can keep the Adding Comment logic on the AddComment of Article, and instead make the Domain Service into something like ICommentAddedProcessor with a CommentAdded() method and have AddComment on Article take a Comment and a ICommentAddedProcessor.

提交回复
热议问题