使用StructureMap和IDbConnection的“按请求”方法 - 连接打开但在执行时关闭

时间:2012-05-24 14:06:00

标签: structuremap dapper

尝试使用StructureMap设置Dapper以使用“按请求”类型的方案。在我的Global.asax中,我有以下内容(从Ayende的旧帖子中修改了NHibernate,我发现在StructureMap中讨论了BuildUp()方法):

protected static IDbConnection CreateConnection() { 
    var settings = ConfigurationManager.ConnectionStrings["MyConnectionString"];
    var connection = DbProviderFactories.GetFactory(settings.ProviderName).CreateConnection();
    if (connection == null) { 
        throw new ArgumentNullException("connection");
    }
    connection.ConnectionString = settings.ConnectionString;
    return connection;
}

public static IDbConnection CurrentConnection { 
    get { return (IDbConnection)HttpContext.Current.Items["current.connection"]; }
    set { HttpContext.Current.Items["current.connection"] = value; }
}

public Global() { 
    BeginRequest += (sender, args) => { 
        CurrentConnection = CreateConnection();
        CurrentConnection.Open(); 
    };

    EndRequest += (sender, args) => { 
        if (CurrentConnection == null) return;
        CurrentConnection.Close();
        CurrentConnection.Dispose();
    }
}

void Application_Start(object sender, EventArgs e) { 
    ObjectFactory.Initialize(x => { 
        x.For<IDbConnection>().Singleton().Use(CreateConnection());
        x.For<ICustomerRepository>().Use<CustomerRepository>();
        x.SetAllProperties(y => y.OfType<ICustomerRepository>());
    });
}

// BasePage.cs
public class BasePage : System.Web.UI.Page { 
    public IDbConnection CurrentConnection { get; set; }

    public BasePage() { 
        ObjectFactory.BuildUp(this);
    }
}

每次我尝试调用它时,实际查询都会失败并显示一条错误,指出Connection的当前状态已关闭,尽管BeginRequest处理程序上的断点显示正在连接上调用Open()。

如果我在每个存储库方法中的IDbConnection上手动调用Open和Close似乎有效,但我试图避免在可能的情况下执行此操作。

1 个答案:

答案 0 :(得分:1)

您将连接创建为单身人士。这意味着只有一个连接对象用于整个应用程序页面。您在Application_Start处理程序中新建的连接从不会被页面使用,因为它们将从容器中获取连接。

你最好使用这样的东西:

void Application_Start(object sender, EventArgs e) { 
    ObjectFactory.Initialize(x => { 
        x.For<IDbConnection>().HttpContextScoped().Use(() => CreateConnection());
        ...
    }
}

 public Global() { 
    EndRequest += (sender, args) => { 
        ObjectFactory.GetInstance<IDbConnection>.Dispose();
    }
 }