Search code examples
c#asp.net-corehangfire

Sending a daily summary email with hang-fire and ASP.NET Core


I need to send a daily summary email to all users but I am unsure where exactly I should trigger it.

I have made a class for sending the emails :

public class SummaryEmailBusiness
{
    private MyDbContext _db;
    private IEmailSender _emailSender;

    public SummaryEmailBusiness(MyDbContext db, IEmailSender emailSender)
    {
        _db = db;
        _emailSender = emailSender;
    }

    public void SendAllSummaries()
    {
        foreach(var user in _db.AspNetUsers)
        {
            //send user a summary
        }
    }
}

Then in ConfigureServices() I have registered service and hangfire:

services.AddHangfire(config =>
    config.UseSqlServerStorage(Configuration.GetConnectionString("DefaultConnection")));

services.AddTransient<SummaryEmailBusiness>();

And in Configure() added

app.UseHangfireDashboard();
app.UseHangfireServer();

Now I am stuck. Hang-fire docs say I need to do something like :

RecurringJob.AddOrUpdate(() =>  SendAllSummaries() , Cron.Daily);

I am not sure how to do this so that the class gets initiated with dependent services injected. How do I reference the SendAllSummaries() method of instantiated service?

What is best way to do this?


Solution

  • All you need to do is just register job (somewhere after calling UseHangfireServer) like this:

    RecurringJob.AddOrUpdate<SummaryEmailBusiness>(x => x.SendAllSummaries(), Cron.Daily);
    

    Doing services.AddHangfire already registers special JobActivator which not only resolves job instances from asp.net core DI container, but also creates new scope for each job, which is important in your case, because most likely your MyDbContext is registered as scoped.