This package provides StructureMap support for Hangfire, allowing nested StructureMap containers to resolve job type instances and their dependencies, and to manage the lifetime of resolved instances.
Install the Hangfire.StructureMap package from NuGet:
Install-Package Hangfire.StructureMap
To configure Hangfire to use StructureMap, configure your container and call the IGlobalConfiguration
extension method, UseStructureMapActivator
:
var container = new Container();
// container.Configure...
GlobalConfiguration.Configuration.UseStructureMapActivator(container);
After configuration, when jobs are started a StructureMap-based implementation of the JobActivator
class is used to resolve job type instances and all of their dependencies.
Hangfire.StructureMap doesn't rely on a specific object lifecycle - you can configure your dependencies as Singleton
, ContainerScoped
, Transient
, AlwaysUnique
or ThreadLocal
as normal.
Hangfire.StructureMap creates a nested container for each job execution, so using ContainerScoped
will scope dependency lifetimes to that of the job.
container.For<IRepository>().ContainerScoped().Use<GenericRepository>();
The nested container is disposed when jobs ends, and all dependencies that implement the IDisposable
interface are also automatically disposed (Singleton
scoped instances are of course an exception).