Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 849
mskuratowski Avatar asked Feb 07 '23 02:02

mskuratowski


1 Answers

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);
like image 77
DavidG Avatar answered Feb 08 '23 14:02

DavidG