RecurringJobs and loc

Hi all, can someone help me please. I am trying to use hangfire to setup a recurring task that recurs every hour. I also want to call this method manually from a web api. I have done all this, apart from the fact that i cannot call my method, because i am using SimpleInjector.

Maybe i am setting this up wrong, if so, please let me know, as only downloaded today.

I have my extension method like so

    public static IApplicationBuilder UseHangFireServer(this IApplicationBuilder builder, Container container, BackgroundJobServerOptions options, JobStorage storage)
    {
        if (builder == null) throw new ArgumentNullException("builder");
        if (options == null) throw new ArgumentNullException("options");
        if (storage == null) throw new ArgumentNullException("storage");

        var server = new BackgroundJobServer(options, storage);
        var lifetime = builder.ApplicationServices.GetRequiredService<IApplicationLifetime>();
        lifetime.ApplicationStopped.Register(server.Dispose);

        // Setup our recurring jobs
        RecurringJob.AddOrUpdate("trigger-queue", () => builder.ApplicationServices.GetService<IMyService>().Queue(), Cron.Hourly);

        return builder;
    }

But build.ApplicationServices.GetService() is returning NULL.

I have tried this as well

// Setup our recurring jobs

RecurringJob.AddOrUpdate("trigger-queue", () => container.GetService<IMyService>().Queue(), Cron.Hourly);

But i get an error saying

The IMyService is registered as ‘Execution Context Scope’ lifestyle, but the instance is requested outside the context of a Execution Context Scope.

Can someone please help me?

Hi, if you need to resolve service which has in IoC container defined lifetime “per request” or similar one, then resolving such instance needs HttpContext. Unfortunatelly this context is not available when performing background job (or recurrent job). Threrefore, you need to setup different instance lifetime in your IoC container.

My solution to this was to just service locate my work in the job:

RecurringJob.AddOrUpdate(job.name, () => 
    ((IScheduledJob) container.GetInstance(jobtype)).JobAction(), job.cronExpression);

IScheduledJob is my own interface i use to scan for jobs and register them automatically. container is a local copy of the static reference to StructureMap