Try Playground
Show / Hide Table of Contents

Extensible Database Dependency Usage and Implementation [Deprecated]

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

  • .NET
  • Legacy API
  • 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.
  • Create a new Console Application.
  • Make sure that the data being added is serializable.
  • Add NCache References by locating %NCHOME%\NCache\bin\assembly\4.0 and adding Alachisoft.NCache.Web and Alachisoft.NCache.Runtime as appropriate.
  • Include the Alachisoft.NCache.Runtime.Dependencies namespace in your application.

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.

  • .NET
  • Legacy API
[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
}
[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;
        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;
    }

    public override bool HasChanged
    {
        get
        {
            return DetermineExpiration();
        }
    }
}

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.

  • .NET
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.

  • .NET
  • Legacy API
// 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);
string connString = "Provider=SQLOLEDB.1; Data Source=localhost; User ID=sa; password=; Initial Catalog=Northwind";

// Creating custom dependency
CustomDependency customDependency = new CustomDependency(123, connString);

Product product = new Product();
product.ProductID = 1001;
product.ProductName = "Chai";

string key = "Product:" + product.ProductID;
// Adding data with custom dependency
cache.Insert(key, product, new CacheDependency(customDependency), Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Default);

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

In This Article
  • Step 1: Implement Extensible Database Dependency Class
  • Step 2: Implement Custom Dependency Provider
  • Step 3: Deploy Implementation on Cache
  • Step 4: Use Extensible Dependency
  • Additional Resources
  • See Also

Contact Us

PHONE

+1 (214) 764-6933   (US)

+44 20 7993 8327   (UK)

 
EMAIL

sales@alachisoft.com

support@alachisoft.com

NCache
  • NCache Enterprise
  • NCache Professional
  • Edition Comparison
  • NCache Architecture
  • Benchmarks
Download
Pricing
Try Playground

Deployments
  • Cloud (SaaS & Software)
  • On-Premises
  • Kubernetes
  • Docker
Technical Use Cases
  • ASP.NET Sessions
  • ASP.NET Core Sessions
  • Pub/Sub Messaging
  • Real-Time ASP.NET SignalR
  • Internet of Things (IoT)
  • NoSQL Database
  • Stream Processing
  • Microservices
Resources
  • Magazine Articles
  • Third-Party Articles
  • Articles
  • Videos
  • Whitepapers
  • Shows
  • Talks
  • Blogs
  • Docs
Customer Case Studies
  • Testimonials
  • Customers
Support
  • Schedule a Demo
  • Forum (Google Groups)
  • Tips
Company
  • Leadership
  • Partners
  • News
  • Events
  • Careers
Contact Us

  • EnglishChinese (Simplified)FrenchGermanItalianJapaneseKoreanPortugueseSpanish

  • Contact Us
  •  
  • Sitemap
  •  
  • Terms of Use
  •  
  • Privacy Policy
© Copyright Alachisoft 2002 - 2025. All rights reserved. NCache is a registered trademark of Diyatech Corp.
Back to top