public class DbContextHelper
{
//一次请求共用一个上下文实例
public static MyDbContext GetCurrentDbContext()
{
#region HttpContext 已经保证了只有一个实例
MyDbContext db = HttpContext.Current.Items["MyDbContext"] as MyDbContext;
if (db == null)
{
db = new MyDbContext();
HttpContext.Current.Items.Add("MyDbContext", db);
}
return db;
#endregion
#region CallContext
MyDbContext dbContext = CallContext.GetData("MyDbContext") as MyDbContext;
if (dbContext == null)
{
dbContext = new MyDbContext();
CallContext.SetData("MyDbContext", dbContext);
}
return dbContext;
#endregion
}
}
public class MyDbContext
{
}