DBContext没有在简单的注入器上处理

时间:2015-11-14 13:37:27

标签: c# asp.net-mvc entity-framework simple-injector

我在Simple Injector 3.1.0中注册了以下内容:

container.RegisterForWeb<AppContext>(() => new EFAppContext(
    @"DefaultConnection", 
    new PetaPocoDispatcher(@"DefaultConnection")));

在这个RegisterForWeb方法中,我有:

var hybridLifestyle = Lifestyle.CreateHybrid(
    () => HttpContext.Current != null,
    new WebRequestLifestyle(),
    new LifetimeScopeLifestyle());

container.Register<TService>(instance, hybridLifestyle);

我的EFAppContext类是IdentityDbContext

的扩展名
public class EFAppContext : IdentityDbContext<ApplicationUser, CustomRole, int, 
    CustomUserLogin, CustomUserRole, CustomUserClaim>, 
    AppContext
{
    ...
}

我按照教程查找EF6 codeproject上的泄漏连接。并扩展了本教程,以便能够查看此泄漏连接正在执行哪个Query。我发现每次我向服务器发出请求时,都会打开一个新连接,但从未关闭。它唯一的查询是:

IF db_id(N'DB_MySystem_TEST') IS NOT NULL 
    SELECT 1 ELSE SELECT Count(*) 
    FROM sys.databases 
    WHERE [name]=N'DB_MySystem_TEST'

这是我的代码或Simple Injector的问题吗?我从未遇到过Simple Injector 2.8.0的这个问题。

1 个答案:

答案 0 :(得分:0)

我的EFAppContext类有一个构造函数,如果数据库存在,每次都会验证:

public class EFAppContext : IdentityDbContext<ApplicationUser, CustomRole, int, 
    CustomUserLogin, CustomUserRole, CustomUserClaim>, 
    AppContext
{
    if (!this.Database.Exists())
        this.Database.CreateIfNotExists();
    ...
}

而且我不知道为什么它强迫我的连接保持打开状态。所以我用一个交易包裹它:

public class EFAppContext : IdentityDbContext<ApplicationUser, CustomRole, int, 
    CustomUserLogin, CustomUserRole, CustomUserClaim>, 
    AppContext
{
    using (var dbContextTransaction = this.Database.BeginTransaction())
    {
        try
        {
            if (!this.Database.Exists())
                this.Database.CreateIfNotExists();
            dbContextTransaction.Commit();
        }
        catch
        {
            dbContextTransaction.Rollback();
        }
    }
    ...
}

现在,我的连接被处理掉了。剩下的唯一问题是为什么......

相关问题