16.8. Caching Application Data Based on Database Dependencies
Your application draws on data stored in database that is expensive to create from a performance perspective, so you want to store the data in memory, where it can be accessed by users throughout the lifetime of the application. The problem is that the data changes occasionally and you need to refresh the data when it changes.
Configure your SQL Server database and add the
<sqlCacheDependency> element to web.config as described in Recipe 16.5, store the data in the Cache with a
SqlCache-Dependency, and access the data in the Cache as required in your application.
The application we have implemented to demonstrate the solution is shown in Examples 16-7, 16-8 through 16-9. Example 16-7 shows the .aspx file used to display the cached data, and Examples 16-8 (VB) and 16-9 (C#) show the code-behind classes for the page.
ASP.NET 2.0 has added a
SqlCacheDependency class that can be used to create a dependency to data in a database. The
SqlCacheDependency class uses the same infrastructure described in Recipe 16.5 to determine if the data in the database has changed and to cause the data to expire in the Cache when it has.
Once the configuration of SQL Server and the
<sqlCacheDependency> element has been added to your web.config, as described in Recipe 16.5, adding data to the Cache with a dependency to data in the database is easy. All that is required is to create an instance of a
SqlCacheDependency class ...