UNIT of Work Design Pattern

323 1 0
                                    

Are you new to Design patterns?

What is the use of UNIT of Work design pattern?

What is “WORK” and “UNIT” in software application?

Logical transaction! = Physical CRUD

So this can be achieved by using simple transactions?

So how can we achieve the same?

C# Sample code for unit of work

Step 1:- Create a generalized interface (IEntity) for business objects

Step 2:- Implement the “IEntity” interface

Step 3:- Create the unit of work collection

Step 4:- See it working

Home work

Source code of Unit of work design pattern

Are you new to Design patterns?

In case you are completely new to Design patterns you can start from the below code project articles:-

Design pattern Part 1(factory, abstract factory, builder, prototype, shallow and deep prototype, singleton and command patterns).

Design pattern Part 2 (Interpeter , Iterator, mediator, memento and  observer design pattern).

Design pattern Part 3 (state pattern,stratergy,visitor,adapter and flyweight pattern).

Design pattern Part 4(Bridge Pattern, Composite Pattern, Facade Pattern, Chain Of Responsibility, Proxy Pattern and Template pattern).

What is the use of UNIT of Work design pattern?

Unit of work design pattern does two important things first it maintains in-memory updates and second it sends these in-memory updates as one transaction to the database.

So to achieve the above goals it goes through two steps:-

It maintains lists of business objects in-memory which have been changed (inserted, updated or deleted) during a transaction.

Once the transaction is completed, all these updates are sent as one BIG UNIT OF WORK to be persisted physically in database one GO.

What is “WORK” and “UNIT” in software application?

A simple definition of Work means performing some task.  From software application perspective WORK is nothing but inserting, updating and deleting data. For instance let’s say you have application which maintains customer data in to database.

So when you add, update or delete a customer record on the database it’s 1 UNIT. In simple words the equation is.

 Collapse | Copy Code

1 customer CRUD = 1 unit of work

Where CRUD stands for creates, read, update and delete operation on a single customer record.

Logical transaction! = Physical CRUD 

The equation which we discussed in the previous section changes a lot when it comes to real world scenarios. Now consider the below scenario where every customer can have multiple addresses.  Then many rows will be come 1 unit of work.

For example you can see in the below figure customer “Shiv” has 2 addresses, so for the below scenario the equation is:-

 Collapse | Copy Code

3 Customer CRUD = 1 Logical unit of work

So in simple words transactions for all of the 3 records should succeed or all of them should fail. It should be 

UNIT of Work Design PatternWhere stories live. Discover now