User Profile Caching Sample

Lets assume we have a profile page in our site that is generated using several queries. We might have a model for this page e.g. UserProfile class that contains all profile data for a user, and a GetProfile method that produces this for a particular user id.

  1. public class UserProfile
  2. {
  3. public string Name { get; set; }
  4. public List<CachedFriend> Friends { get; set; }
  5. public List<CachedAlbum> Albums { get; set; }
  6. ...
  7. }
  1. public UserProfile GetProfile(int userID)
  2. {
  3. using (var connection = new SqlConnection("..."))
  4. {
  5. // load profile by userID from DB
  6. }
  7. }

By making use of LocalCache.Get method, we could cache this information for one hour easily and avoid DB calls every time this information is needed.

  1. public UserProfile GetProfile(int userID)
  2. {
  3. return LocalCache.Get<UserProfile>(
  4. cacheKey: "UserProfile:" + userID,
  5. expiration: TimeSpan.FromHours(1),
  6. loader: delegate {
  7. using (var connection = new SqlConnection("..."))
  8. {
  9. // load profile by userID from DB
  10. }
  11. }
  12. );
  13. }