cachingservicestackfilterattribute

Why is ServiceStack caching in Service, not FilterAttribute?


In MVC and most other service frameworks I tried, caching is done via attribute/filter, either on the controller/action or request, and can be controlled through caching profile in config file. It seems offer more flexibility and also leave the core service code cleaner.

But ServiceStack has it inside the service. Are there any reason why it's done this way?

Can I add a CacheFilterAttribute, but delegate to service instead?

 ToOptimizedResultUsingCache(base.Cache,cacheKey,()=>   {
     // Delegate to Request/Service being decorated?
 });

I searched around but couldn't find an answer. Granted, it probably won't make much difference because the ServiceStack caching via delegate method is quite clean. And you seldom change caching strategy on the fly in real world. So this is mostly out of curiosity. Thanks.


Solution

  • Because the caching pattern involves, checking first to see if it is cached, if not to then execute the service, populate the cache, then return the result.

    A Request Filter doesn't allow you to execute the service and a Response Filter means that the Service will always execute (i.e. mitigating the usefulness of the Cache), so the alternative would require a Request + Response filter combination where the logic would be split into 2 disjointed parts. Having it inside the Service, lets you see and reason about how it works and what exactly is going on, it also allows full access to calculate the uniqueHashKey used and exactly what and when (or even if) to Cache, which is harder to control with a generic black-box caching solution.

    Although we are open to 'baking-in' built-in generic caching solutions (either via an attribute or ServiceRunner / base class). Add a feature request if you'd like to see this, specifying the preferred functionality/use-case (e.g. cache based on Time / Validity / Cache against user-defined Aggregate root / etc).