Extensible Dependency Usage and Implementation
Note
This feature is only available in NCache Enterprise Edition.
In extensible dependency, the users can have their own dependencies scenarios. In this way, items can be expired from cache in a number of flexible ways where expiration logic meets the user’s business requirements. To implement extensible dependency in your application, NCache provides an abstract class ExtensibleDependency
. Follow the guide below to understand how to implement and use this class.
Kindly refer to Custom Cache Dependencies to get acquainted with all cache dependency custom methods provided by NCache.
Step 1: Implement ExtensibleDependency Class
Pre-requisites
- The class must be implemented as a Class Library (.dll) in Visual Studio. This will be deployed on NCache cluster.
- Install the following NuGet packages in your application:
- To override the
ExtensibleDependency
class, include the following assembly in your application:Alachisoft.NCache.Runtime.Dependencies
- The class implementing
ExtensibleDependency
must be marked asSerializable
, along with any parameters the process code might be taking in.
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.
[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();
}
OleDbDataReader reader = null;
int availableUnits = -1;
OleDbCommand command = connection.CreateCommand();
command.CommandText = String.Format(CultureInfo.InvariantCulture,
"Select UnitsInStock From Products" +
" where ProductID = {0}", productID);
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 your logic of extensible dependency on server side. Here's how you can implement your own extensible dependency provider:
Pre-Requisites
- Install the following NuGet packages in your application:
- To utilize the APIs, include the following namespaces in your application:
Alachisoft.NCache.Runtime.Dependencies
Alachisoft.NCache.Runtime.CustomDependencyProviders
Alachisoft.NCache.Runtime
Alachisoft.NCache.Runtime.Exceptions
- This should be a class library project.
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
{
// Exception
}
}
public void Dispose ()
{
// Dispose off all resources
}
}
Step 3: Deploy Implementation on Cache
Deploy this class and any dependent assemblies on NCache by referring to Deploy Providers in Administrator’s Guide for help.
Step 4: Use Extensible Dependency
Once extensible dependency class has been implemented and deployed, it is ready to be used in your application.
Pre-Requisites for Using Extensible Dependency
- Install the following NuGet packages in your application:
- To utilize the Insert API, include the following namespaces in your application:
Alachisoft.NCache.Client
Alachisoft.NCache.Runtime.Dependencies
Alachisoft.NCache.Runtime.Exceptions
- The
Dependency
class must be deployed on cache. - The application must be connected to cache before performing the operation.
- Cache must be running.
- To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
The following code shows how to add data into the cache using the Insert
method with extensible dependency:
try
{ // 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);
}
catch (OperationFailedException ex)
{
// Exception can occur due to:
// Connection Failures
// Operation Timeout
// Operation performed during state transfer
}
catch (Exception ex)
{
// Any generic exception like ArgumentNullException or ArgumentException
}
Additional Resources
NCache provides 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
Data Source Providers (Backing Source)