使用Hangfire for ASP.NET Core的触发器控制器方法

问题描述 投票:0回答:1

美好的一天,

我试图在ASP.NET Core中的Controller中触发某个命令。

我已经安装了hangfire并配置了我的Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddHangfire(x => x.UseSqlServerStorage('my conn string'));
    ...
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    ...
    // add hangfire
    app.UseHangfireDashboard();
    app.UseHangfireServer();    
    ...
}

但问题是,我的样本控制器有多个依赖注入

public class ProductsController: Controller
{
    private readonly ISomething1 something1;
    private readonly ISomething2 something2;
    private readonly ISomething3 something3;

    public ProductsController(ISomething1 something1, ISomething2 something2, ISomething3 something3){
        this.something1 = something1;
        this.something2 = something2;
        this.something3 = something3;
    }

    public async Task<IActionResult> TriggerMe(){
        ...
    }
}

我正试图在我的启动时实现这样的东西

RecurringJob.AddOrUpdate(
() => // trigger the TriggerMe() controller method ,
Cron.Daily);

有什么帮助吗?谢谢

c# asp.net-core asp.net-core-2.0 hangfire
1个回答
0
投票

UPDATE 由于Rotavita与控制器,视图等紧密耦合,我建议分两步解决这个问题

  1. 使用RazorEngine从视图生成HTML(用于报告/电子邮件目的,将该视图与普通视图分开),您只需要视图/模板路径和模型(包含要呈现的值)
  2. 使用HTML使用wkhtmltopdf生成PDF(Rotavita在引擎盖下使用此库)

原版的

调用controller实例是由框架完成的一个过程,它不应该由cron作业调用或调用。 对于您的问题,您只需要添加对方法或委托的引用。假设您要将代码移动到其他类。

var instance=new Foo();
RecurringJob.AddOrUpdate(() => instance.DoSomething,Cron.Daily);

Foo

public class Foo
{
    public void DoSomething()
    {
    //your code
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.