Ramesh
Ramesh

Reputation: 13266

Simple Injector's Lifestyle as Caching Solution

I am using Simple Injector as IoC container to inject my dependencies. Currently there are set of Master Data which I am relying on and the class which builds this Master data is marked as singleton to avoid frequent calls to DB.

But this puts me in trouble that I am unable to invalidate and object and fresh new data. Absolute time cache policy should be suffice my current need.

To introduce Caching I can think of below approaches

  1. Use Decorator pattern to introduce Caching layer.
  2. Use Interceptor to introduce caching layer.
  3. Use the Lifestyle hook as caching solution (as described here).

I am more tempted towards the option #3.

I would like to get an expert opinion on whether it would be the right approach to take and possible pitfalls other than the one mentioned in the above link.

Upvotes: 2

Views: 425

Answers (1)

Steven
Steven

Reputation: 172606

You should not create your own custom lifestyle, because:

  • This means that you are caching data in your application components, which make them stateful, which is something you should strive to prevent. Making components stateless simplifies development, because it makes it easier to reason about such component.
  • As already noted in the documentation you are pointing at, the given "Absolute Expiration" lifestyle might cause trouble, because "even though locking is used to synchronize access, this custom lifestyle might not work as expected, because when the expiration time passes while an object graph is being resolved." Such problem can be quite hard to solve.

I would say that a decorator approach would yield the best results. Here the decorator should not hold the cache itself (because that would make it stateful and mutable, but instead delegate this to an external service, like MemCache or perhaps something that is either bound to the request or the session.

Upvotes: 2

Related Questions