【发布时间】:2020-01-16 00:49:29
【问题描述】:
我刚刚在我的 MVC 网站中安装了 Hangfire 包。 我创建了一个 Startup 类
[assembly: OwinStartup(typeof(Website.Startup))]
namespace Website
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
Hangfire.ConfigureHangfire(app);
Hangfire.InitializeJobs();
}
}
}
还有一个 Hangfire 课程
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(), "* * * * *");
}
}
另外,我在单独的类库中创建了一个新作业
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);
}
}
}
所以当我运行应用程序时,在 Hangfire 的仪表板中我收到以下错误:
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)
所以,我有点迷路了。我错过了什么?
【问题讨论】:
-
你有注册码,hangfire 会在其中收到关于它应该使用哪些类的通知?
-
我想我没有。我不记得读过那个。你能告诉我更多吗?
-
好吧,我不是hangfire 专家,但很明显它正在尝试解决
CurrencyRatesJob,但它不能,因为它不知道IBudgetsRepository应该解决什么问题。这就是为什么你会得到 no empty constructor 错误。也许这篇文章可以帮助stackoverflow.com/questions/26615794/…。 -
@MarianEne 在下面查看我的回复,这会处理注入依赖项和您已经遇到的问题。