开发者

Is it a bad idea to have multiple UnitOfWork instances open at a time (ASP.Net Applicaiton)?

开发者 https://www.devze.com 2023-03-13 02:16 出处:网络
I have an application I am working on, using Entity Framework 4.1 as my data access layer. I have created several repositories that work with different entities. Each repository, as part of the constr

I have an application I am working on, using Entity Framework 4.1 as my data access layer. I have created several repositories that work with different entities. Each repository, as part of the constructor, takes in a UnitOfWork object. I then created an abstraction to those repositories with services layers. Each layer creates a UnitOfWork that is then passed to its respective repository.

In my service layer, should I only be opening one UOW that can be used by all the services I have created? I开发者_如何学C haven’t run into any issues, yet, but wanted to know if what I am doing can possibly cause issues.

As a note, in my web application, I am only working with one entity type at a time when inserting an updating data. My concern came when I had to instantiate one service for the main entity and then possibly another service to read in static data that comes from a configuration table in the database.


You can have as many unit of work instances as you need within single request processing. Unit of work represents single logical operation.

For simplicity (and in most cases it is enough) developers usually use a new single unit of work for each request because each request usually represents one logical operation. But you can find scenarios where this will not be enough. In such case you will need multiple unit of works and probably also multiple repositories (each set associated with one unit of work).


If you have multiple units of work you WILL eventually have problems, because if you try to relate an entity from one context (unit of work) to an entity from another context, you'll have a change tracker collision.

Assuming you have a business layer called .Task or some such, each Task should instantiate a unit of work and pass it into the repositories it calls, since it is the task, not the repo, which should know how entities are to be brought together.

It's ok to have a repo default a UOW by default if one isn't provided - but that can lead to lax task coding where you end up creating a repo w/o a UOW then using its output in something that has its own UOW.

Avoid one common static unit of work, as well - since again, the task, not the repo or the model, should be deciding when changes should be applied.


No, you should only have a single UoW open at a time. I would recommend using a Factory to provide a single instance of your UoW per HTTP Request.

You can find a sample implementation here: Entity Framework 4 CTP 4 / CTP 5 Generic Repository Pattern and Unit Testable

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号