2014-09-18 80 views
0

我有一个CommandHandler,它为一个对象实现了一些逻辑并提交了上下文(在我的例子中是RavenDb IDocumentSession)。我需要为一组对象实现相同的逻辑。第一个想法是创建一个新的CommandHandler,它将为每个对象的foreach调用第一个CommandHandler。但是这会导致N次数据库往返。在对象集合的命令中重用对象的命令

我最好的想法是创建一个基本的CommandHandler与逻辑本身,但没有上下文提交。类似这样的:

internal class AuditProductCommandHandler : AuditProductCommandHandlerBase, ICommandHandler<AuditProductCommand> 
{ 
    private readonly IDocumentSession _documentSession; 

    public AuditProductCommandHandler(IDocumentSession documentSession) 
    { 
     _documentSession = documentSession; 
    } 

    public void Execute(AuditProductCommand command) 
    { 
     AuditProduct(command.Product); 

     _documentSession.SaveChanges(); 
    } 
} 

internal class AuditProductsCommandHandler : AuditProductCommandHandlerBase, ICommandHandler<AuditProductsCommand> 
{ 
    private readonly IDocumentSession _documentSession; 

    public AuditProductsCommandHandler(IDocumentSession documentSession) 
    { 
     _documentSession = documentSession; 
    } 

    public void Execute(AuditProductsCommand command) 
    { 
     foreach (var product in command.Products) 
     { 
      AuditProduct(product); 
     } 

     _documentSession.SaveChanges(); 
    } 
} 

internal class AuditProductCommandHandlerBase 
{ 
    protected void AuditProduct(Product product) 
    { 
     //logic itself 
    } 
} 

出于某种原因,我对此解决方案感到不舒服。有没有更好的选择?

回答

1

我会建议从命令处理程序实现中删除_documentSession.SaveChanges(),并将责任移交给调用者。然后调用者可以决定是否必须链接多个命令处理程序或多个数据库操作,然后再调用SaveChanges()。由于调用者负责创建/发送对象,因此他们也可以负责保存和处理该对象。