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

查看:168
本文介绍了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.

我不是很熟悉,但团结的原则是这样的:

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天全站免登陆