使用HttpContextScoped时(StructureMap不处理数据上下文) [英] StructureMap is not disposing data context when using HttpContextScoped()

查看:274
本文介绍了使用HttpContextScoped时(StructureMap不处理数据上下文)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是有一个数据上下文中的每ASP.NET MVC HTTP请求( MainDbContext )和处理数据上下文的请求结束时。

My goal is to have one data context (MainDbContext) per HTTP request in ASP.NET MVC and dispose the data context when the request ends.

我用下面的StructureMap配置:

I'm using the following StructureMap configuration:

public static class ContainerConfigurer
{
    public static void Configure()
    {
        ObjectFactory.Initialize(x =>
        {
            x.For<MainDbContext>().HttpContextScoped();
        });
    }
}

每当我需要一个 MainDbContext ,我用这个code:

var dbContext = ObjectFactory.GetInstance<MainDbContext>();

这是按预期工作:正在每个HTTP请求创建只有一个数据上下文。问题是, MainDbContext 没有被设置在请求结束。

This is working as expected: only one data context is being created per HTTP request. The problem is, MainDbContext is not being disposed at the end of the request.

我如何配置我的ObjectFactory处置数据上下文的HTTP请求完成时?还是这只是我需要用手工做的 Application_EndRequest()在Global.asax中。

How can I configure my ObjectFactory to dispose the data context when the HTTP request finishes? Or is this just something I need to do manually using Application_EndRequest() in Global.asax.

更新

我只是想加入以下code到Global.asax中:

I just tried adding the following code to Global.asax:

protected virtual void Application_EndRequest()
{
    ObjectFactory.GetInstance<MainDbContext>().Dispose();
}

正如预期的那样,这解决了问题。我还在想,如果有任何的方式与StructureMap自动做到这一点,但是。

As expected, this solves the problem. I'm still wondering if there's any way to do this automatically with StructureMap, however.

推荐答案

<击>而不是:

x.For<MainDbContext>().HttpContextScoped();

尝试:

x.For<MainDbContext>().HttpContextScoped().Use(() => new MainDbContext());

此外,通常它是需要一个分贝范围内库类。因此,而不是 ObjectFactory.GetInstance&LT; MainDbContext&GT;(); 有你的仓库采取一些接口分贝范围内,并配置StructureMap注入 MainDbContext 放进去。然后,让StructureMap注入到库控制器,...

Also normally it's repository classes that need a db context. So instead of ObjectFactory.GetInstance<MainDbContext>(); have your repositories take some interface db context and configure StructureMap to inject the MainDbContext into them. Then make StructureMap inject repositories into controllers, ...

Application_EndRequest

protected void Application_EndRequest()
{
    ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects();
}

这篇关于使用HttpContextScoped时(StructureMap不处理数据上下文)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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