This package provides Lamar support for Hangfire, allowing nested Lamar containers to resolve job type instances and their dependencies, and to manage the lifetime of resolved instances.
Install the Hangfire.Lamar package from NuGet:
Install-Package Hangfire.Lamar
To configure Hangfire to use Lamar, configure your container and call the IGlobalConfiguration
extension method, UseLamarActivator
:
var container = new Container();
// container.Configure...
GlobalConfiguration.Configuration.UseLamarActivator(container);
After configuration, when jobs are started a Lamar-based implementation of the JobActivator
class is used to resolve job type instances and all of their dependencies.
Hangfire.Lamar doesn't rely on a specific object lifecycle - you can configure your dependencies as Singleton
, Scoped
or Transient
as normal.
Hangfire.Lamar creates a nested container for each job execution, so using Scoped
will scope dependency lifetimes to that of the job.
var container = new Container(c =>
c.For<IRepository>().Use<GenericRepository>().Scoped();
);
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, and are only disposed when the root container is disposed).