Typically in my ASP.NET MVC application that uses Unity
as dependency framework i use PerRequestLifetimeManager
which disposes all the dependencies when HTTP request completes.
Now i configured Hangfire into ASP.NET application. Hangfire schedules a background job that has dependency on DBContext
. Something like below
(The IGenericRepository use DBContext but for brevity purpose that code is not shown here)
public interface IMyService:IDisposable
{
void DoWork();
}
public class MyService : IMyService
{
private bool _disposed = false;
protected readonly IGenericRepository _repository = null;
public MyService(IGenericRepository repository)
{
_repository = repository ?? throw new ArgumentNullException(nameof(repository));
}
public void DoWork()
{
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
{
if (_repository != null)
{
_repository.Dispose();
}
// Free any other managed objects here.
}
// Free any unmanaged objects here.
_disposed = true;
}
}
}
and then on application startup i register a recurring job like below
RecurringJob.AddOrUpdate<IMyService>(x => x.DoWork(), Cron.Hourly());
I understand that i cannot use PerRequestLifetimeManager
because there wont be HttpContext available when Hangfire schedules a background job.
But i wanted to know what lifetime manager i should be using here to register IGenericRepository
and IMyService
so that Dispose method will get invoked implicitly as soon as the job is done.