I have a MVC application that uses IoC with Unity and I have a DbContext
implementation defined using the PerRequestLifetimeManager
. This object is injected to controllers through Unit of Work implementation.
container.RegisterType<DBContext, MyContext>(new PerRequestLifetimeManager());
Everything is working fine so far and the app has a decent number of models and controllers. Now what I was trying to do recently is add some automated tasks for this application and for this purpose I wanted to use HangFire.
I've set up this library in my project and created a simple task in which I want to invoke an action that requires a DBContext
.
RecurringJob.AddOrUpdate(() => MyTask(), Cron.Daily);
and MyTask()
is defined as follows
public void MyTask()
{
var taskManager = container.Resolve<ITaskManager>();
taskManager.DoSomething();
}
Task manager requires an instance of DBContext (through Unit of Work object)
public class TaskManager : ITaskManager
{
public TaskManager(IUnitOfWork uow) {
...
}
}
public class UnitOfWork : IUnitOfWork
{
public class UnitOfWork(DBContext context) {
...
}
}
Now the problem I have is whenever the task runs I get the exception saying PerRequestLifetimeManager can only be used in the context of an HTTP request
.
Is there a way I could inject this object without HTTP request or how can I change my Unity configuration to also support my HangFire tasks?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…