欢迎拍砖,我在Web应用程序下,使用线程单例模式管理EF ObjectContext
为什么我要用单例模式,类似如下代码
......
Employee emp1 = model1.GetEmployeeById(10);
......
emp1.Name = "Employee Name1";
......
model2.Method(emp1);
......
mode3.Update(emp1);
如果在 model1, model2, model3 的方法中都要针对 emp1 访问数据库,则在这些模块的方法内部可能需要都 new 出 ObjectContext 对象,类似这样:
MyObjectContext db = new MyObjectContext ();
var query =
from obj in db.Employees
where obj.Id = id
select obj;
但是这样一来,这些操作就不在同一个 ObjectContext 下管理了,同时也不好使 model1, model2, model3 逻辑放在同一个事务中。
如果使用线程单例模式,也就是提供一个工厂方法,保证同一个线程调用工厂方法得到的是同一个对象,而不同的线程调用工厂方法得到的是不同对象,则处理起来就方便多了
public partial class MyObjectContext {
[ThreadStatic]
private static MyObjectContext instance;
public static MyObjectContext CurrentInstance {
get {
if (instance == null)
instance = new MyObjectContext();
return instance;
}
}
public static void ReleaseCurrent() {
if (instance != null) {
try {
instance.Dispose();
} catch { }
}
instance = null;
}
}