【问题标题】:How/where to create a void method in CQRS pattern如何/在哪里创建 CQRS 模式中的 void 方法
【发布时间】:2022-01-26 19:01:14
【问题描述】:

我正在尝试在干净的架构中实现 CQRS 模式。

我知道如果是 commads/query,那么我需要在 applictionLayer 中添加一个名为 commads/query 的文件夹。

现在我想创建一个 void 方法。不是命令或查询它只是一个无效的方法。我想在我的查询和命令中再次使用它。

public void FormatSomethingHtml(Something something)
{
  something.FinePrint = _helper.FormatHtml(something.FinePrint, something.SiteCode.Name);
  // removed rest      
}

我不知道应该在哪里创建这个方法。

如果我在 commandHandler 中创建此方法,我将无法重用它。 即:

public class UpdateSomethingCommandHandler : IRequestHandler<UpdateSomethingCommand, Something>
{   
    // removed rest
    public void FormatSomethingHtml(Something something)
    {
        something.FinePrint = _helper.FormatHtml(something.FinePrint, something.SiteCode.Name);
        // removed rest      
    }
}

在上面的方法中,我可以在 UpdateSomethingCommandHandler 中使用。 但我无法在另一个处理程序中重用它。 IE。当我这样打电话时 new UpdateSomethingCommandHandler.FormatSomethingHtml(something);我出错了。

哪里可以创建通用方法?

【问题讨论】:

  • 您可以将该类注册为单例(到您的 DI 中),它通过接口公开 FormatSomethingHtml 方法。您可以在 UpdateSomethingCommandHandler 的 ctor 中要求它。

标签: c# asp.net-core cqrs


【解决方案1】:

这应该是一个实用服务并将其注入您需要的任何查询/处理程序中。

例如:

public interface IFormatService
{
void FormatSomethingHtml(Something something)
}

public class HtmlFormatService: IFormatService
{
public void FormatSomethingHtml(Something something)
{
  something.FinePrint = _helper.FormatHtml(something.FinePrint, something.SiteCode.Name);
  // removed rest      
}
}

在您的处理程序中,您将注入它并像使用任何其他服务一样使用它

另外,我会考虑将返回类型更改为Something,这样您就可以更新对象并返回ot,或者只是接受一个字符串并返回格式化的字符串,如下所示:

public string FormatSomethingHtml(string something)
{
  return _helper.FormatHtml(something.FinePrint, something.SiteCode.Name);
}

在您的处理程序/查询中

var something = new Something();
something.Fingerprint = _formatter.FormatSomethingHtml(...)

【讨论】:

    猜你喜欢
    • 2021-10-30
    • 1970-01-01
    • 2020-05-13
    • 2015-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-02
    相关资源
    最近更新 更多