I have a somewhat complex permission system that uses six database tables in total and in order to speed it up, I would like to cache these tables in memory instead of having to hit the database every page load.
However, I'll need to update this cache when a new user is added or a permission is changed. I'm not sure how to go about having this in memory cache, and how to update it safely without causing problems if its accessed at the same time as updating
Does anyone have an example of how to do something like this or can point me in the right direction for research?
Without knowing more about the structure of the application, there are lots of possible options. One such option might be to abstract the data access behind a repository interface and handle in-memory caching within that repository. Something as simple as a private IEnumerable<T>
on the repository object.
So, for example, say you have a User
object which contains information about the user (name, permissions, etc.). You'd have a UserRepository
with some basic fetch/save methods on it. Inside that repository, you could maintain a private static HashSet<User>
which holds User
objects which have already been retrieved from the database.
When you fetch a User
from the repository, it first checks the HashSet
for an object to return, and if it doesn't find out it gets it from the database, adds it to the HashSet
, then returns it. When you save a User
it updates both the HashSet
and the database.
Again, without knowing the specifics of the codebase and overall design, it's hard to give a more specific answer. This should be a generic enough solution to work in any application, though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With