简体   繁体   English

在ASP.NET MVC Action方法内部调用时,Hangfire作业无法触发

[英]Hangfire job not firing when called inside of ASP.NET MVC Action method

The hangfire job does not start when putting it inside of an Index method in MVC. 将hangfire作业放入MVC中的Index方法中时,它不会启动。 I can't figure out why. 我不知道为什么。

[HttpGet]
public IActionResult Index()
{
     RecurringJob.AddOrUpdate(() => GetCurrentUserNotifications(User.Identity.Name), Cron.MinuteInterval(1));

      return View(vm);
}

public void GetCurrentUserNotifications(string userId)
{

    _connectionManager.GetHubContext<NotificationsHub>()
        .Clients.All.broadcastNotifications(_repository.GetNotifications()
        .Where(x => x.DateTime <= DateTime.Now && x.CreatedBy == userId));
}

The problem is your method GetCurrentUserNotifications(string userId) is a method of your controller class. 问题是您的方法GetCurrentUserNotifications(string userId)是您的控制器类的方法。 When Hangfire execute the job, it will try to create an instance of your controller class. 当Hangfire执行作业时,它将尝试创建控制器类的实例。 But I believe your controller class does not have a parameter less constructor. 但我相信您的控制器类没有参数少的构造函数。 So it will fail to execute the job. 因此它将无法执行作业。 The solution is to create a separate class, for example BackgroundProcess . 解决方案是创建一个单独的类,例如BackgroundProcess Put your GetCurrentUserNotifications in to it, and call like below: 将您的GetCurrentUserNotifications放入其中,并按如下所示进行调用:

RecurringJob.AddOrUpdate(() => new BackgroundProcess().GetCurrentUserNotifications(User.Identity.Name), Cron.MinuteInterval(1));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM