MikeB
MikeB

Reputation: 51

ServiceStack caching strategy

I'm learning ServiceStack and have a question about how to use the [Route] tag with caching. Here's my code:

[Route("/applicationusers")]
[Route("/applicationusers/{Id}")]
public class ApplicationUsers : IReturn<ApplicationUserResponse>
{
    public int Id { get; set; }
}

public object Get(ApplicationUsers request)
{
    //var cacheKey = UrnId.Create<ApplicationUsers>("users");
    //return RequestContext.ToOptimizedResultUsingCache(base.Cache, cacheKey, () => 

    return new ApplicationUserResponse
    {
        ApplicationUsers = (request.Id == 0)
                 ? Db.Select<ApplicationUser>()
                 : Db.Select<ApplicationUser>("Id = {0}", request.Id)
    };
}

What I want is for the "ApplicationUsers" collection to be cached, and the times when I pass in an Id, for it to use the main cached collection to get the individual object out.

If I uncomment the code above, the main collection is cached under the "users" key, but any specific query I submit hits the Db again. Am I just thinking about the cache wrong?

Thanks in advance, Mike

Upvotes: 1

Views: 418

Answers (1)

rudygt
rudygt

Reputation: 75

this line

var cacheKey = UrnId.Create<ApplicationUsers>("users");

is creating the same cache key for all the requests, you must use some of the request parameters to make a "unique key" for each different response.

var cacheKey = UrnId.Create<ApplicationUsers>(request.Id.ToString());

this will give you the "urn:ApplicationUsers:0" key for the get all and the "urn:ApplicationUsers:9" for the request with Id = 9

now you can use the extension method in this way.

 return RequestContext.ToOptimizedResultUsingCache(Cache, cacheKey, () => {
                                                                               if(request.Id == 0) return GetAll();
                                                                               else return GetOne(request.Id);
                                                                           });

I hope this helps, regards.

Upvotes: 2

Related Questions