分解式与PerRequestLifetimeManager没有HTTP请求分解、PerRequestLifetimeManager、HTTP

由网友(自由都给你)分享简介:我有一个使用IoC和统一一个MVC应用程序,我必须使用 PerRequestLifetimeManager A 的DbContext 实现定义。这个对象是通过工作实施单位注入控制器。I have a MVC application that uses IoC with Unity and I have a DbCo...

我有一个使用IoC和统一一个MVC应用程序,我必须使用 PerRequestLifetimeManager A 的DbContext 实现定义。这个对象是通过工作实施单位注入控制器。

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());

一切工作正常,到目前为止并在应用程序有模型和控制器体面一些。现在,我试图最近做的就是为这个应用程序添加一些自动化的任务,并为这个目的,我想用迟发型。

我已经建立了这个库在我的项目,并创造了我想要调用,需要一个操作简单的任务的DbContext

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);

MyTask的()定义如下:

public void MyTask()
{
    var taskManager = container.Resolve<ITaskManager>();
    taskManager.DoSomething();
}

任务管理器要求(通过工作目标的单位)的DbContext实例

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) {
        ...
    }
}

现在我的问题是每当任务运行我得到的异常说法 PerRequestLifetimeManager只能在HTTP请求的上下文中使用

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.

有没有办法,我可以不用HTTP请求注入这个对象还是我怎样才能改变我的统一配置,也支持我的迟发型任务?

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?

推荐答案

我已经使用 PerRequestLifetimeManager 这个问题很感动了。我现在已经开始使用 HierarchicalLifetimeManager 与容器层次来代替,然后你需要设置你的应用程序来创建每个预期范围的一个新的子容器(如请求或工作),并配置了子容器时范围内完成。

I have moved away from using PerRequestLifetimeManager for this very issue. I have now started using HierarchicalLifetimeManager with container hierarchies instead and then you need to set up your app to create a new child container per intended scope (such as a request or a job) and dispose that child container when that scope is complete.

有一些库,挂接到MVC和的WebAPI创建每个请求一个新的子容器。快速搜索找到这一个MVC: Unity.Mvc5 和官方的

阅读全文

相关推荐

最新文章