Cie*_*eja 4 c# asp.net dependency-injection hangfire asp.net-core
我想在我的ASP.NET核心应用程序中使用Hangfire,我有错误消息:
没有注册类型服务
这是我的代码:服务:
public class MyService: IMyService
{
private readonly MyContext _context;
public MyService(MyContext context)
{
_context = context;
}
// some code
}
public interface IMyService
{
//some code
}
Run Code Online (Sandbox Code Playgroud)
在Startup.cs中:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IMyService, MyService>();
// another services
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider serviceProvider)
{
app.UseHangfireDashboard();
app.UseHangfireServer();
RecurringJob.AddOrUpdate(() => serviceProvider.GetService<IMyService>().MyMethod(), Cron.Minutely);
}
Run Code Online (Sandbox Code Playgroud)
你知道服务没有注册的原因吗?
Hangfire挂钩到已经存在的依赖注入,因此您不需要使用serviceProvider.GetService来获取对象.而是使用适当的Hangfire函数让它解决依赖关系:
RecurringJob.AddOrUpdate<IMyService>(s => s.MyMethod(), Cron.Minutely);
Run Code Online (Sandbox Code Playgroud)