Hello,
I’ve just installed Hangfire package in my MVC website. I’ve created a Startup class
[assembly: OwinStartup(typeof(Website.Startup))]
namespace Website
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
Hangfire.ConfigureHangfire(app);
Hangfire.InitializeJobs();
}
}
}
and a Hangfire class
public class Hangfire
{
public static void ConfigureHangfire(IAppBuilder app)
{
app.UseHangfire(config =>
{
config.UseSqlServerStorage("DefaultConnection");
config.UseServer();
config.UseAuthorizationFilters();
});
}
public static void InitializeJobs()
{
RecurringJob.AddOrUpdate<CurrencyRatesJob>(j => j.Execute(), "* * * * *");
}
}
Also, I’ve created a new job in a separate class library
public class CurrencyRatesJob
{
private readonly IBudgetsRepository budgetsRepository;
public CurrencyRatesJob(IBudgetsRepository budgetsRepository)
{
this.budgetsRepository = budgetsRepository;
}
public void Execute()
{
try
{
var budgets = new BudgetsDTO();
var user = new UserDTO();
budgets.Sum = 1;
budgets.Name = "Hangfire";
user.Email = "email@g.com";
budgetsRepository.InsertBudget(budgets, user);
}
catch (Exception ex)
{
var message = ex.ToString();
throw new NotImplementedException(message);
}
}
}
So when I run the application, in the Hangfire’s dashboard I get the following error:
Failed An exception occurred during job activation.
System.MissingMethodException
No parameterless constructor defined for this object.
System.MissingMethodException: No parameterless constructor defined for this object.
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.Activator.CreateInstance(Type type)
at Hangfire.JobActivator.ActivateJob(Type jobType)
at Hangfire.Common.Job.Activate(JobActivator activator)
So, if I define a parameterless constructor in this job, I’ll lose the IBudgetRepository object, which is not good. (I tried giving it a parameterless constructor, and the job was executed, but as I was saying I didn’t have the IBudgetRepository).
I am using Ninject for DI purposes and I’ve seen that there is a Hangfire.Ninject Nuget package, but I’m not sure how to solve this issue.