3

I am getting List of Users from other application using webservice. I am getting all the Info.

  List<User> users = ws.SelectUsers();

I want to store this list of users in between controller actions so that I dont want to hit web service everytime for their roles and other Info.

What would be the best way to do this using C# and MVC

I w

PhillyNJ
  • 3,859
  • 4
  • 38
  • 64
Chatra
  • 2,989
  • 7
  • 40
  • 73
  • Is this list unique to the user or common to the application? – Joel Etherton Feb 27 '15 at 17:39
  • Asp.net Http Cache works for me. – Ako Feb 27 '15 at 17:44
  • 2
    possible duplicate of [How to cache data in a MVC application](http://stackoverflow.com/questions/343899/how-to-cache-data-in-a-mvc-application) – Ako Feb 27 '15 at 17:46
  • 1
    Yep. As someone will inevitably chime in here and tell you to use `Session` or `TempData`, let's just cut that off at the head, and say cache the result of the web service call. Then, for each request you check the cache for that data and use it if it exists or call the web service again to populate it if it doesn't. – Chris Pratt Feb 27 '15 at 18:14
  • @Ako Why not answer using that? :) – Ian CT Feb 27 '15 at 18:34
  • @JoelEtherton Unique to the user. – Chatra Feb 27 '15 at 18:51
  • @ChrisPratt: The better solution unless the application has a tendency to rapidly cycle or round robin on load balanced servers. – Joel Etherton Feb 27 '15 at 18:54
  • @JoelEtherton: It's actually the best solution with load balancing. Worst case scenario, the web service just gets hit again. Eventually all the load balanced servers will populate their own caches, assuming you don't have some centralized cache in the first place. However, using something like `Session` would be highly prone to error in such an environment. – Chris Pratt Feb 27 '15 at 18:57

1 Answers1

3

You can use the MemoryCache to store things. The below example would store the users for an hour in cache. If you needed to store it on a per user basis you could change it slightly so that the cache key ("Users" in the below example) is generated using the users ID or something.

MemoryCache cache = MemoryCache.Default;
string baseCacheKey = "Users";

public void DoSomethingWithUsers(int userId)
{
    var cacheKey = baseCacheKey + userId.ToString();
    if (!cache.Contains(cacheKey))
    {
        RefreshUserCache(userId);
    }
    var users = cache.Get(cacheKey) as List<User>

    // You can do something with the users here
}

public static RefreshUserCache(int userId)
{
    var users = ws.SelectUsers();

    var cacheItemPolicy = new CacheItemPolicy();
    cacheItemPolicy.AbsoluteExpiration = DateTime.Now.AddHours(1);
    var cacheKey = baseCacheKey + userId.ToString();
    cache.Add(cacheKey, users , cacheItemPolicy);
}

Edit: I've included the option for a userId if you do want to do it per user

Neil Mountford
  • 1,951
  • 3
  • 21
  • 31