StructureMap,ASP.NET和Entity Framework DbContext dispose

时间:2013-03-28 16:08:57

标签: asp.net-mvc entity-framework structuremap

我有一个ASP.NET MVC应用程序,它使用EF来处理数据库。我使用DDD作为架构,我得到了存储库和服务模式。

我正在尝试使用StructureMap进行DI,但出于某种原因,我的数据库在第一次请求后被处理掉了。

编辑:我遇到的错误是

  

由于DbContext已经完成,因此无法完成操作   地布置。

似乎我在存储库中获取它,例如:

public class AccountRepository : Repository<Account>, IAccountRepository
{
    public AccountRepository(MyDbContext context) : base(context) { }

    public Account FindAccountByEmailAddress(string emailAddress, bool loadRelatedRoles = false)
    {
        IQueryable<Account> query = (from a in Entity
                                     where a.LoweredEmailAddress == emailAddress.ToLower()
                                     select a);
        if (loadRelatedRoles)
        {
            return query.Include(a => a.Roles).FirstOrDefault();
        }

        return query.FirstOrDefault();
    }
}

在Application_BeginRequest中,我正在使用

注册数据库
        ObjectFactory.Configure(x =>
        {
            x.For(typeof(MyDbContext))
                .HttpContextScoped();
        });

为了将其保留为每个请求一个实例。

在Application_EndRequest中,我使用:

发布请求
    protected void Application_EndRequest(object sender, EventArgs e)
    {
        StructureMap.ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects();
    }

我错过了什么吗?或者我的approch没问题,我的Repository实现可能存在问题,这使得它成为现实。

1 个答案:

答案 0 :(得分:1)

好的,我发现了问题 - 似乎我的Application_Start代码被多次调用,并且在某些情况下我使用了Lazy - 这导致了对DB上下文的空引用的保存。

感谢您的帮助!

相关问题