Alachisoft NCache 4.1 - Online Documentation

Custom Dependency

 
NOTE: This feature is not available in NCache Express and Professional edition.
 
You can have your own custom dependencies. In this way, you can expire items from the cache in a number of flexible ways where your own expiration logic meets your business requirements. NCache provides an abstract class ExtensibleDependency that is the base for all the dependencies. All you need to do is to inherit your dependency class from this class and override its HasChanged property. The following sample code creates a new dependency. The dependency polls the Northwind database and expires all the Products for which units in stock are less than 100.
 
Include the following namespaces in your application:
 
using Alachisoft.NCache.Runtime.Dependencies;
using Alachisoft.NCache.Web.Caching;
 
[Serializable]
public class CustomDependency : ExtensibleDependency
{
    private string _connString;
    private int _productID;
 
    public override bool Initialize() { return false; }
 
    public CustomDependency(int productID, string connString)
    {
        _connString = connString;
        _productID = productID;
    }
    internal bool DetermineExpiration()
    {
        if (GetAvailableUnits(_productID) < 100)
            return true;
        return false;
    }
    internal int GetAvailableUnits(int productID)
    {
        OleDbDataReader reader = null;
        OleDbConnection connection = new OleDbConnection(_connString);
        connection.Open();
        int availableUnits = -1;
        try
        {
            OleDbCommand cmd = connection.CreateCommand();
            cmd.CommandText = String.Format(CultureInfo.InvariantCulture,
            "Select UnitsInStock From Products" +
            " where ProductID = {0}", productID);
            reader = cmd.ExecuteReader();
            if (reader.Read())
            {
                availableUnits = Convert.ToInt32(reader["UnitsInStock"].ToString());
            }
            reader.Close();
            return availableUnits;
        }
        catch (Exception)
        {
            return availableUnits;
        }
    }
    public override bool HasChanged
    {
        get
        {
            return DetermineExpiration();
        }
    }
}
 
Here is how CustomDependency will be used:
 
Cache _cache = NCache.InitializeCache("mycache");
 
string connString = "Provider=SQLOLEDB.1;Data Source=localhost;User ID=sa;password=;Initial Catalog=Northwind";
 
CustomDependency hint = new CustomDependency(123, connString);
 
_cache.Add("myKey", "myVal", new CacheDependency(hint), Cache.NoAbsoluteExpiration, new TimeSpan(0,0,10),  CacheItemPriority.High);
       
                
See Also
 
Copyright © 2005-2012 Alachisoft. All rights reserved.