Aggregate Cache Dependency
NCache also allows you to use different strategies in combination with the same cache data in the form of Aggregate Cache Dependency. Aggregate Cache Dependency allows you to associate multiple dependencies of different types with a single cached item. For example, you can associate key dependency and file dependency with an item using aggregate dependency and data will be invalidated based on whichever dependency triggers first.
Aggregate Cache Dependency associates one cached item with a collection of
dependency objects which can be any other dependency provided by NCache e.g.
CacheDependency
, DBCacheDependency
or any combination of these.
AggregateCacheDependency
monitors a collection of dependency objects so that
when any of them changes, the cached object becomes obsolete and is removed from
the cache.
Combining different invalidation strategies provides you with more flexible ways to meet your application needs in different environments.
NCache provides feature of Aggregate dependency to support multiple dependencies
with a single cache item. The following code explains how to add
AggregateCacheDependency
with an item.
To utilize the API, include the following namespace in your application:
Alachisoft.NCache.Runtime.Dependencies.
Product product1 = new Product();
product1.ProductID = 1001;
product1.ProductName = "Chai";
string key1 = "Product:" + product.ProductID;
//Add item
cache.Add(key1, product1);
//Create dependent object
Product product2 = new Product();
product2.ProductID = 1002;
product2.ProductName = "Coffee";
string key2 = "Product:" + product.ProductID;
string filepath = "D:\\tempProductList.txt"; //file dependency
try {
//Initializing Aggregate Dependency; item dependent on key of product1
AggregateCacheDependency aggregateDependency = new AggregateCacheDependency();
aggregateDependency.Dependencies.Add(new FileDependency(filepath));
aggregateDependency.Dependencies.Add(new KeyDependency(key));
//Adding new item with AggregateCacheDependency
cache.Add(key2, product2, aggregateDependency, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal);
}
catch (OperationFailedException e){
// handle exception
}