ASP.NET MVC inject per request

后端 未结 3 994
抹茶落季
抹茶落季 2020-12-09 14:25

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

3条回答
  •  旧巷少年郎
    2020-12-09 14:45

    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
         (new ContainerControlledLifetimeManager());
    }
    
    Application_EndRequest(...)
    {
      var container = HttpContext.Items["container"] as IUnityContainer
      if(container != null)
        container.Dispose();
    }
    

提交回复
热议问题