I am a year late to this party, and stumbled across this question whilst looking for something Hangfire related, figured I would answer as there is no answer to the question being asked.
You absolutely can use Dependency Injection in Hangfire without having to rely on default constructors or instantiating within your class.
You can inherit from JobActivator
and override the ActivateJob(Type)
method, while your custom implementation uses the IServiceProvider
.
public class DependencyJobActivator : JobActivator
{
private readonly IServiceProvider _serviceProvider;
public DependencyJobActivator(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public override object ActivateJob(Type jobType) {
return _serviceProvider.GetService(jobType);
}
}
Then simply tell Hangfire to use your custom implementation in the Startup class' Configure
method.
public void Configure(IApplicationBuilder app, IServiceProvider serviceProvider)
{
app.UseHangfireDashboard();
app.UseHangfireServer(new BackgroundJobServerOptions { Activator = new DependencyJobActivator(serviceProvider) });
app.UseMvc();
}
Read more here on the Hangfire Documentation
RecurringJob.AddOrUpdate("MyMethodNameAsID", () => Class.Method(), Cron.Minutely);
I think would work... Maybe. If I understood your question correctly. – Gabbard