views:

39

answers:

3

In my design, I have Repository classes that get Entities from the database (How it does that it does not matter). But to save Entities back to the database, does it make sense to make the repository do this too? Or does it make more sense to create another class, (such as a UnitOfWork), and give it the responsibility to save stuff by having it accept Entities, and by calling save() on it to tell it to go ahead and do its magic?

+1  A: 

I would give the repository the overall responsibility for encapsulating all aspects of load and save. This ensures that tricky issues such as managing contention between readers and writes has a place to be managed.

The repository might well use your UnitOfWork class, and might need to expose a BeginUow and Commit methods.

djna
+3  A: 

In DDD, Repositories are definitely where ALL persistence-related stuff is expected to reside.

If you had saving to and loading from the database encapsulated in more than one class, database-related code will be spread over too many places in your codebase - thus making maintenance significantly harder. Moreover, there will be a high chance that later readers of this code might not understand it at first sight, because such a design does not adhere to the quasi-standards that most developers are expecting to find.

Of course, you can have separate Reader/Writer-helper classes, if that's appropriate in your project. But seen from the Business Layer, the only gateway to persistence should be the repository...

HTH!
Thomas

Thomas Weller
+1  A: 

Fowler says that repository api should mimic collection:

A Repository mediates between the domain and data mapping layers, acting like an in-memory domain object collection.

Arnis L.