Location of caching code in a domain-managed project

In an application that followed a domain-driven project, where you have the following types of concepts

  • The repository that deals with database access
  • An application service that coordinates the interaction between objects and value objects, etc.

where in general would you put caching code to eliminate an expensive database call?

I have seen code bases that are simply cached everywhere, and it’s hard to control memory usage and it’s hard to provide recommendations to other developers.

Please understand that I know that you need to cache data only when you need, I just ask a general question.

+6
caching dns domain-driven-design
source share
2 answers

The great thing about abstract repositories is that you can use the Decorator pattern to implement cross-cutting issues like caching.

As an example, given the IMyRepository interface, you can create a MyCachingRepository similar to this pseudocode:

public class MyCachingRepository : IMyRepository { private readonly IMyRepository repository; public MyCachingRepository(IMyRepository repository) { if(repository == null) { throw new ArgumentNullException("repository"); } this.repository = repository; } public Foo SelectFoo(int id) { Foo foo = ... // attempt to get foo from cache if // foo is not it cache { foo = this.repository.SelectFoo(id); // save foo in cache } return foo; } } 

In this example, GetFoo is defined by IMyRepository. Please note that the decorated repository is called only if the item is not found by the cache.

This follows the principle of a single replacement , as the actual caching implementation may focus on retrieving and storing data, while Decorator caching may focus on caching. This allows you to change two independently of each other.

In our current project, we used this approach, and what is nice is that we could do this as an afterthought, without even touching the original repositories. This is in the spirit of the Open / Closed principle .

+10
source share

I would put it in the repository. Repositories must be defined by the contract, and the use of the cache must be hidden behind this contract, therefore it is transparent to the consumer of the repository.

+2
source share

All Articles