Can I override Dispose to make an entity class that always calls SaveChanges?

你离开我真会死。 提交于 2019-12-04 12:06:02

Don't do this. It's a bad idea.

The purpose of "Dispose" is to politely dispose of an unmanaged resource early so that other processes can use it. "Dispose" should not have semantics -- it should not change the state of your program or be required in some way. It should only do precisely what it says it does: dispose of a resource.

Should you do it in the finalizer? Absolutely not. That's even worse. The finalizer might not run at all, the finalizer runs on another thread, the finalizer can be called even if the object wasn't properly initialized, and so on. Writing a finalizer is almost never the right thing to do, and if you do write a finalizer it should only dispose of a resource. Do not do anything fancy in a finalizer; you will almost certainly write a dangerously incorrect and brittle program if you do.

The right principle to cleave to here is: if a call is required for semantic reasons then force the user to put the call in the code. If they forget to do it, they'll find out in testing. Let the user decide whether it is the right thing to do to put the call in a finally block or not. Don't make that decision for them; you might decide wrong.

  1. Dispose is where you would do this, if you were to do it at all.

  2. This is one of the reasons you should not do it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!