Own service - no services registered for type

I would like to use Hangfire in my ASP.NET Core application, I got an error message:

No service for type is registered

Here is my code: Services:

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 an idea why the service is not registered?

+4
source share
1 answer

Hangfire connects to dependency injection already in place, so you don't need to use serviceProvider.GetServiceto get your object. Instead, use the appropriate Hangfire function to resolve this dependency:

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

Source: https://habr.com/ru/post/1655042/


All Articles