When you developing WCF RIA domain services you usually highly coupled with underlying data access layer (DAL) technology of your choice. It’s usually Entity Framework (EF), LinqToSQL, nHibernate, pure ADO.NET or other ORM/DAL frameworks. It’s great, however it brings following issues
- Learning curve for some ORM/DAL frameworks can be painful (it may include convoluted APIs with leaking abstractions)
- Due to coupling it’s hard/impossible to switch to new DAL framework if you bump into some major issues with you current one
- Lack of testability with some of ORM/DAL frameworks
That’s why it makes sense to introduce another level of abstraction/indirection between your domain logic and DAL. It must be simple, testable and well known concept. Well, and we have one – it’s famous Repository pattern.
There are many ways you can define/implement it, let’s consider my version. In this example we will implement generic repository for EF’s entities. First of all – let’s define abstraction
As you can see our repository is quite succinct. It can do two things – Query for data and CRUD. And it seems that learning curve for using this abstraction is minimal (read - developers will love it)
As long as we trying to adapt standard code generated by EF designer for our repository needs we need to introduce some more interfaces to abstract away our custom ObjectContext
This is abstraction for EF’s ObjectContext which is essentially implementation of UnitOfWork (UoW) pattern. However it’s not only UoW, it’s also entity sets container, which can be abstracted away by
ok, so far so good, now we need to make our custom ObjectContext (generated by EF designer) to implement this abstraction. It can be easily done by partial class like this
great, now we can implement our generic repository
As you can see our generic repository mixes Repository and UnitOfWork patterns, which will allow us to do batch data modifications and save in one go.
The usage of this generic class is simple, elegant and straightforward
You may wonder what is that magical DataContext our Repository depends on? Well, wait for the next post ;)
to be continued…