Cieja Cieja - 2 months ago 91
ASP.NET (C#) Question

Own service - no service for type has been registered

I would like to use Hangfire in my ASP.NET Core app, bu I have got error message:


No service for type has been registered


Here's my code:
Service:

public class MyService: IMyService
{
private readonly MyContext _context;

public MyService(MyContext context)
{
_context = context;
}

// some code
}

public interface IMyService
{
//some code
}


In 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);
}


Do you have any idea why service is not registered?

Answer

Hangfire hooks into the dependency injection already in place so you don't need to use serviceProvider.GetService to get your object. Instead use the appropriate Hangfire function to let it resolve the dependency:

RecurringJob.AddOrUpdate<IMyService>(s => s.MyMethod(), Cron.Minutely);