Mar*_*Ene 5 c# scheduler hangfire
我刚刚在我的MVC网站上安装了Hangfire包.我创建了一个Startup类
[assembly: OwinStartup(typeof(Website.Startup))]
namespace Website
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
Hangfire.ConfigureHangfire(app);
Hangfire.InitializeJobs();
}
}
}
Run Code Online (Sandbox Code Playgroud)
和一个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(), "* * * * *");
}
}
Run Code Online (Sandbox Code Playgroud)
另外,我在一个单独的类库中创建了一个新工作
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
因此,当我运行应用程序时,在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)
Run Code Online (Sandbox Code Playgroud)
所以,我在这里有点失落.我错过了什么?
您似乎没有将Hangfire连接到您正在使用的IoC容器,因此它使用其默认策略来创建请求的类型,在您的特定示例中,这意味着调用:
System.Activator.CreateInstance(typeof(CurrencyRatesJob));
Run Code Online (Sandbox Code Playgroud)
由于CurrencyRatesJob该类没有默认的无参数构造函数,因此失败并显示您在问题中显示的错误消息.
要将Hangfire连接到IoC基础结构,您需要创建自己的JobActivator类来覆盖该ActivateJob方法,并使用配置的IoC容器来创建所请求的作业类型的实例.
UnityJobActivator可以在此处找到使用Unity作为容器()的示例,可以在此处找到Funqcontainer(FunqJobActivator)的示例.
Hangfire文档中描述了该过程,Hangfire github repo提供了几种容器类型的标准实现
| 归档时间: |
|
| 查看次数: |
4219 次 |
| 最近记录: |