C# 使用HangFire的正确架构

C# 使用HangFire的正确架构,c#,hangfire,C#,Hangfire,我即将开始在asp.net mvc web应用程序中使用C#中的hangfire,并想知道如何创建正确的体系结构 由于我们将使用HangFire,我们将它用作消息队列,因此我们可以直接处理(存储在数据库中)用户数据,然后通知其他系统,稍后在单独的过程中发送电子邮件。 所以我们的代码现在看起来像这样 function Xy(Client newClient) { _repository.save(newClient); _crmConnector.notify(newClient); mailer

我即将开始在asp.net mvc web应用程序中使用C#中的hangfire,并想知道如何创建正确的体系结构

由于我们将使用HangFire,我们将它用作消息队列,因此我们可以直接处理(存储在数据库中)用户数据,然后通知其他系统,稍后在单独的过程中发送电子邮件。 所以我们的代码现在看起来像这样

function Xy(Client newClient)
{
_repository.save(newClient);
_crmConnector.notify(newClient);
mailer.Send(repository.GetMailInfo(), newClient)
}
现在我们想把最后两行放在队列上

因此,按照hangfire网站上的示例,我们可以这样做

var client = new BackgroundJobClient();
client.Enqueue(() => _crmConnector.notify(newClient));
client.Enqueue(() => mailer.Send(repository.GetMailInfo(), newClient));
但我想知道这是否是正确的解决方案

我曾经读过关于将项目放入队列的文章,这些被称为“commands”,它们是专门创建的类,用于包装任务/命令/要做的事情并将其放入队列

因此,对于通知crm连接器,这将是

client.Enqueue(() => new CrmNotifyCommand(newClient).Execute();
然后,crmnotify命令将接收新客户端,并具有执行
\u crmConnector.notify(newClient)的知识。

在这种情况下,放入队列(由HangFire执行)的所有项目都将包装在一个“命令”中。 这样的命令将是一个自包含类,它知道如何执行一种业务功能。当命令本身使用多个其他类时,我想它也可以称为facade

你觉得这样的架构怎么样

我曾经读过一篇关于将项目放入队列的文章,这些文章被称为 “commands”,它们是专门为包装 任务/命令/要做的事情并将其放入队列

是的,你的直觉是正确的

您应该将所有依赖项和显式功能封装在一个单独的类中,并告诉Hangfire只执行一个方法(或命令)

这是我的例子,我从中得出


如果您需要进一步澄清,我鼓励您观看

namespace HangfireDemo.Core.Demo
{
    public interface IDemoService
    {
        void RunDemoTask(PerformContext context);
    }

    public class DemoService : IDemoService
    {
        [DisplayName("Data Gathering Task <a href=\"jira.contoso.com\">Confluence Page</a>")]
        public void RunDemoTask(PerformContext context)
        {
            Console.WriteLine("This is a task that ran from the demo service.");
            BackgroundJob.ContinueJobWith(context.BackgroundJob.Id, () => NextJob());
        }

        public void NextJob()
        {
            Console.WriteLine("This is my next task.");
        }
    }
}
BackgroundJob.Enqueue("demo-job", () => this._demoService.RunDemoTask(null));