尝试使用 StructureMap 设置 Dapper 以利用“按请求”类型的场景。在我的 Global.asax 中,我有以下内容(修改自 Ayende 涉及 NHibernate 的旧帖子,我发现其中讨论了BuildUp()
StructureMap 中的方法):
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);
}
}
每次我尝试调用它时,实际查询都会失败,并显示连接的当前状态已关闭,尽管 BeginRequest 处理程序上的断点显示正在连接上调用 Open()。
如果我在每个存储库方法内的 IDbConnection 上手动调用 Open 和 Close 似乎可行,但我试图尽可能避免这样做。