Extensible Database Dependency Usage and Implementation
In Extensible Database Dependency, the users can have their own dependency scenarios that invalidate an item when certain criteria are met. In this way, items can expire from the cache in several flexible ways where the expiration logic meets the users business requirements. To implement the Extensible Dependency in your application, NCache provides an abstract class, ExtensibleDependency
. Follow the guide below to understand how to implement and use this class.
Tip
Refer to Custom Cache Dependencies to get acquainted with all cache dependency custom methods provided by NCache.
Prerequisites
- To learn about the standard prerequisites required to work with all NCache server-side features including Extensible Database Dependency, please refer to the given page on Server-Side API Prerequisites.
- The project must be implemented as a Class Library (.dll) in Visual Studio. This will be deployed on the NCache cluster.
- The
Dependency
class must be deployed on cache. - For API details, refer to: ICache, CacheItem, insert, ExecuteReader, CustomDependency, ExtensibleDependency, HasChanged, IDictionary, CommandText, CreateDependency, ICustomDependencyProvider.
Step 1: Implement Extensible Database Dependency Class
The first step in introducing your own logic for Extensible Dependency is to inherit the ExtensibleDependency
class.
Let's suppose there is a grocery store that has a large collection of products that customers often buy. These products can be cached from the database to check their units in stock. The following dependency implementation polls the Northwind database and expires all the Products for which units in stock are less than 100.
[Serializable]
public class Dependency : ExtensibleDependency
{
// Class parameters
[NonSerialized]
OleDbConnection connection;
public Dependency(int productId, string connString)
{
connection = new OleDbConnection(connString);
connection.Open();
productID = productId;
}
public bool HasChanged()
{
if (GetAvailableUnits(productID) < 100)
return true;
return false;
}
internal int GetAvailableUnits(int productID)
{
if (connection == null)
{
connection = new OleDbConnection(connString);
connection.Open();
}
OleDbCommand command = connection.CreateCommand();
command.CommandText = String.Format(CultureInfo.InvariantCulture,
"Select UnitsInStock From Products" +
" where ProductID = {0}", productID);
int availableUnits = -1;
OleDbDataReader reader = null;
reader = command.ExecuteReader();
if (reader.Read())
{
availableUnits = Convert.ToInt32(reader["UnitsInStock"].ToString());
}
reader.Close();
return availableUnits;
}
protected void DependencyDispose()
{
// Dispose off all resources
}
// This class is to be deployed in NCache
}
Step 2: Implement Custom Dependency Provider
A Custom Dependency Provider for Extensible Dependency implements the logic that you created in Step 1 on the server side. Here's how you can implement your own Extensible Dependency Provider:
This class implements the CustomDependencyProvider
interface that is required to successfully create and deploy an Extensible Dependency Provider.
public class ExtensibleDependencyProvider : ICustomDependencyProvider
{
public void Init(IDictionary<string, string> parameters, string cacheName)
{
// Initialize cache and class parameters
}
public Dependency CreateDependency(string key, IDictionary<string, string> dependencyParameters)
{
int productId = 0;
string connectionString = "";
if (dependencyParameters != null)
{
if (dependencyParameters.ContainsKey("ProductID"))
productId = Int32.Parse(dependencyParameters["ProductID"]);
if (dependencyParameters.ContainsKey("ConnectionString"))
connectionString = dependencyParameters["ConnectionString"];
// Create extensible dependency
Dependency dependency = new Dependency(productId, connectionString);
return dependency;
}
else
{
// No parameters found
}
}
public void Dispose ()
{
// Dispose off all resources
}
}
Step 3: Deploy Implementation on Cache
Deploy this class and all dependent assemblies on NCache by referring to Deploy Providers in the Administrator’s Guide for help.
Step 4: Use Extensible Dependency
Once the Extensible Dependency class has been implemented and deployed, it is ready to be used in your application.
The following code shows how to add data into the cache using the Insert
method with Extensible Dependency enabled.
// Specify the connection string
string connectionString = ConfigurationManager.AppSettings["connectionstring"];
// Fetch the product to be added to the cache
Product product = FetchProductFromDB(productId);
// Specify the unique key of the item
string key = $"Product:{product.ProductID}";
// Create a cacheItem
var cacheItem = new CacheItem(product);
// Create dictionary for dependency parameters
IDictionary<string, string> param = new Dictionary<string, string>();
param.Add("ProductID", product.Id.ToString());
param.Add("ConnectionString", connectionString);
// Create Extensible Dependency using Provider and Add it to Cache Item
CustomDependency customDependency = new CustomDependency(ConfigurationManager.AppSettings["ProviderName"], param);
cacheItem.Dependency = customDependency;
// Add cacheItem to the cache with dependency
cache.Insert(key, cacheItem);
Additional Resources
NCache provides a sample application for Extensible Dependency on GitHub.
See Also
How to Configure Custom Dependency
Cache Data Dependency on External Source
WAN Replication across Multi Datacenters through Bridge