每个请求注入 ASP.NET MVC [英] ASP.NET MVC inject per request

查看:32
本文介绍了每个请求注入 ASP.NET MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为每个请求注入 EF 上下文.有什么办法可以实现吗?

I need to inject EF context per request. Is there any way to implement it?

推荐答案

解决方案Unity 讨论列表中提议的 是为每个请求创建一个子容器,让该子容器创建 EF 上下文作为 ContainerControlledLifetime,然后在请求的末尾处理子容器.通过这样做,您不必创建自定义 LifetimeManager.

The solution proposed in the Unity Discussion list is to create a child container per request, have that child container create the EF context as ContainerControlledLifetime, then have the child container disposed at the end of the request. By doing so you don't have to create a custom LifetimeManager.

我对 Unity 不是很熟悉,但原理是这样的:

I'm not very familiar with Unity but the principle would be something like this:

Application_BeginRequest(...)
{
  var childContainer = _container.CreateChildContainer();
  HttpContext.Items["container"] = childContainer;
  childContainer.RegisterType<ObjectContext, MyContext>
     (new ContainerControlledLifetimeManager());
}

Application_EndRequest(...)
{
  var container = HttpContext.Items["container"] as IUnityContainer
  if(container != null)
    container.Dispose();
}

这篇关于每个请求注入 ASP.NET MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆