Sample Implementation of Custom Dependency
To override the
ExtensibleDependency
class, include the following assembly in your application:Alachisoft.NCache.Runtime
.
ExtensibleDependency Class
Method | Description |
---|---|
Initialize() |
This method can be used to perform tasks like allocating resources and acquiring connections etc. If resources have been successfully acquired, it returns true. If Initialize returns false, NCache removes the item with custom dependency from the cache. |
HasChanged() |
NCache calls HasChanged after every clean interval. If HasChanged returns true, all custom dependent items will be removed from cache. |
Sample Implementation of ExtensibleDependency Class
Follow the following steps to implement custom dependency.
Step 1: Inherit the dependency class from ExtensibleDependency
and override the abstract function and property.
Let's suppose there is a grocery store which has a big collection of those products which customers often buy. These products can be cached from the database to check their units in stock. The dependency polls the Northwind database and expires all the Products for which units in stock are less than 100.
To utilize the
ExtensibleDependency
abstract class, include the following namespace in your application:Alachisoft.NCache.Runtime.Dependencies
.
[Serializable]
public class CustomDependency : ExtensibleDependency
{
private string _connString;
private int _productID;
public override bool Initialize()
{
return true;
}
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)
{
SqlDataReader reader = null;
SqlConnection connection = new SqlConnection(_connString);
connection.Open();
int availableUnits = -1;
try
{
SqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "Select UnitsInStockFrom Products where ProductID=" + 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();
}
}
}
Step 2: Place assembly or executable file of the class overriding ExtensibleDependency
in the [InstallDir]\bin\service
folder and restart the NCache service.