I have a project of business objects and a data layer that could potentially be implemented in multiple interfaces (web site, web services, console app, etc).
My question deals with how to properly implement caching in the methods dealing with data retrieval. I’ll be using SqlCacheDependency to determine when the cached objects need to be expired, but I’m unsure of the best way of implementing the cache itself:
If the library is being used for a web project, I’d like to use HttpRuntime.Cache; however, I’m guessing that would be an issue for console apps.
What is the best way of implementing caching in your data layer for a .Net project when allowing for multiple types of interfaces like this?
If you’re using .net 4.0 you should look into the MemoryCache in the System.Runtime.Caching namespace. This was added into .net 4.0 specifically to address the fact that non-ASP.NET applications had no caching API, or had to ship with a dependency on System.Web and use HttpRuntime.Cache. Alternatively you could look into AppFabric caching, which is client-agnostic but may entail overhead you don’t want to have to deal with.
If you’re on an earlier version of .net then you might find the easiest way is to bite the bullet and take the dependency on System.Web, then you can use HttpRuntime.Cache everywhere – it’s not a perfect solution but it has the virtue of consistency. An alternative would be to look at the Enterprise Library Caching Block, which again is client-agnostic but is not recommended for use in web apps where the HttpRuntime stuff is available.