Correct disposing using Repository and Unit Work patterns with Entity Framework?

后端 未结 1 1655
独厮守ぢ
独厮守ぢ 2021-02-06 00:50

Cheers!I have some doubts about using Unit of Work with Repository. Specially a role of child context from Entity Framework. I have searched a lot of information about this them

1条回答
  •  长情又很酷
    2021-02-06 01:12

    Here's a great article on implementing unit of work using MVC.

    I normally dispose of the unit once the business transaction is complete. For example, if the action was to create a Parent, some children and attached them I dispose immediately once that is finished.

    Added more detail relating to above:

    In rereading your question, it sounds like you want more information about the theory of a unit of work rather than actual implementation, my apologies.

    Here's a better article on MSDN related to that, but I will summarize for you.

    According to Martin Fowler, the Unit of Work pattern "maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems."

    Generally, I use the unit of work pattern to bring together all of the related repositories, to solve concurrency issues while still keeping the repositories separate.

    One of the best ways to use the Unit of Work pattern is to allow disparate classes and services to take part in a single logical transaction. The key point here is that you want the disparate classes and services to remain ignorant of each other while being able to enlist in a single transaction.

    • "Where I should realize disposing and saving?"

    I'm not sure I fully understand your question, but I think you're asking what should be managing the lifecycle of the unit of work?

    Here's another SO post related to this, but the summary is whatever owns the unit of work for the moment, and it's related to how you setup the scope of your unit of work. For example, It can be the business command, or an MVC action.

    • "Is it correctly realize Disposable in Inheritance class of DbContext? After that realize in Repository and Unit of Work or just in Uni fo Work?"

    Do you mean, where should you be disposing of the DbContext? I believe that it should be in the unit of work. If you're creating/disposing of multiple contexts in a single unit of work, maybe you should separate them out into 2 different units.

    • Where put method Save in Unit of Work or Repository?

    Your unit of work is handle the context, and the transactions, and should contain the logic to prevent duplicate updates, because of this your save function should be controlled by your unit of work.

    0 讨论(0)
提交回复
热议问题