For ORMs like EF and NHibernate, multiple places suggest using "context per method" (or per request, per transaction) for web apps and services and using "context per form" for thick clients like WinForms and WPF. In C#, resource disposal with context per method is clean and clear with a using
block.
using (var context = new MyDbContext()) { /* ... */ }
However, using WinForms, there are a few possible places to call context.Dispose()
: FormClosing event, FormClosed event, Finalizer, OnClosing override, OnClosed override, do nothing and let GC collect it.
What is the best way to dispose of "context per form" resources?
答案 0 :(得分:1)
听起来很奇怪,你不必丢弃DbContext(如果你没有自己手动打开连接)
看看这个:
Do I always have to call Dispose() on my DbContext objects? Nope
那就是说,我建议你为每个方法使用一个上下文(并处理它)而不是每个表单,特别是如果你有长期存在的表单。
随着时间的推移,你可能会偶尔遇到过时数据的问题,加上上下文构建并不是一个昂贵的过程。
现在,如果您仍然需要每个表单的上下文,我不认为您将称之为哪个事件会有很大差异