gregpakes
gregpakes

Reputation: 4535

Is there a way to clear a session cache key for all users?

Is there a way to clear a session cache key for all users?

For example, I am storing the users currently selected shop item under the following session key "currentItem". In the management area of the website, I decide to delete that particular shop item. I now want to invalidate all the "currentItem" cache entries across all sessions.

Is there a way to do this?

I realise the example I have given is a little contrived, but it gets the point across. I suspect one solution would be to use the normal Cache api to store all of the users current items. That way I could invalidate them when required.

thanks

Upvotes: 7

Views: 1505

Answers (2)

VMAtm
VMAtm

Reputation: 28355

You can't get all the current Sessions from all users
(Frankly speaking, you can, but I don't recommend this, and still you can read only InProc sessions this way).

So the only thing you can do is something like this:

  • Store in Session only ID of the user cart
  • Add item with corresponding ID to the Cache
  • Then adding the item to the Cache, set the dependency to the Item
  • Then just generate event to change whole carts in Cache.
  • Also you should think about re-creating items if for some reasons Cache is being emptied - you should provide the CacheItemRemovedCallback callback for this event.

Upvotes: 3

Tim M.
Tim M.

Reputation: 54377

You could move the shopping cart to the database. Unless you have a very rapid buying process, or an extremely redundant environment, Session or Cache will probably not be durable enough. Since they are not persisted, you also won't have a direct method to analyze buying decisions, attrition, etc.

Depending on how often your inventory changes, you might only need to validate that a cart item is available at checkout. As a user, it would be very confusing to me to see that an item had just "magically" disappeared from my cart or that the price had changed. It would be better to explicitly call this out, in my opinion.

Again, a database would be a superior solution as you could track the state of the item at the time it was added to the cart against the current definition of the product.

If you must use a Session or Cache-based solution, then @VMAtm's proposed solution is a valid option.

Upvotes: 0

Related Questions