One of my dependencies (DbContext) is registered using the WebApiRequestLifestyle scope.
Now, my background job uses IoC and depends on the service that was registered above using the WebApiRequestLifestyle. I’m wondering how this works when Hangfire calls the method i registered for the background job. Will the DbContext be treated like a transistent object since the web api is not involved?
Any guidance would be great!
It sounds like you’re using SimpleInjector. What I do is use a Hybrid Lifestyle to create the DbContext Scoped for WebApi, and Transient for Background, like so:
// web layer:
private static void InitializeContainer(Container container)
{
ApplicationSimpleInjectorInitializer.InitializeContainer(container, () => HttpContext.Current != null);
}
// application layer:
public static void InitializeContainer(Container container, Func<bool> isWebRequest)
{
DomainSimpleInjectorInitializer.InitializeContainer(container, isWebRequest);
//other registrations here
}
// domain layer
public static void InitializeContainer(Container container, Func<bool> isWebRequest)
{
var lifestyle = Lifestyle.CreateHybrid(isWebRequest, Lifestyle.Scoped, Lifestyle.Transient);
//other registrations here
}