Sharing Autofac IoC resource between Web API & Hangfire

Hello,

I am developing an Asp.NET WebAPI 2 application with Autofac (v3.5.2), Hangfire (v1.5.2) and Hangfire.Autofac 2.0.1.

Currently, I am injecting my EF DBContext into my WebAPI controllers directly (I know this isn’t best practice), but also need to inject them into my Hangfire job as well.

After reviewing the Hangfire.Autofac documentation here, this is apparently supported as stated below:

HTTP Request Warnings

Services registered with InstancePerHttpRequest() method will be unavailable during job activation, you should re-register these services without this hint. If you have components registered for the HTTP request scope, please add an additional scope for them:

builder.RegisterType()
.InstancePerBackgroundJob()
.InstancePerHttpRequest();
HttpContext.Current is also not available during the job performance. Don’t use it!

Unfortunately this does not appear to be the case. If I register my DBContext like so (note I am utilizing InstancePerRequest() as InstancePerHttpRequest() no longer seems to be available):

builder.RegisterType<SMCProject.Models.SMCProjectEntities>()
    .As<SMCProject.Interfaces.ISMCProjectEntities>()
    .InstancePerBackgroundJob()
    .InstancePerRequest();

Depending on the order of InstancePerBackgroundJob() or InstancePerHttpRequest(), either my controller or background job fails to inject properly with the dreaded:

Autofac.Core.DependencyResolutionException: No scope with a Tag matching 'AutofacWebRequest' is visible from the scope in which the instance was requested. This generally indicates that a component registered as per-HTTP request is being requested by a SingleInstance() component (or a similar scenario.) Under the web integration always request dependencies from the DependencyResolver.Current or ILifetimeScopeProvider.RequestLifetime, never from the container itself.

Or:

An error occurred when trying to create a controller of type 'EntriesController'. Make sure that the controller has a parameterless public constructor.

Though I can get both WebAPI & Hangfire playing together properly like so:

builder.RegisterType<SMCProject.Models.SMCProjectEntities>()
    .As<SMCProject.Interfaces.ISMCProjectEntities>()
    .InstancePerLifetimeScope();

This appears to be safe, but I’m curious as to whether it actually is?

Where exactly is the lifetime scope created & disposed of with Hangfire?

What are the implications of using lifetime scope on sharing of resources between jobs?

Thank you!

-CJ