NCache Usage from .NET Application
After NCache has been successfully configured, you can develop your application by embedding the NCache API calls. The NCache client applications can communicate with the cache servers through the GetCache method. This method establishes a connection between the client and server and returns a cache handle. You can use this handle for Add
, Insert
, Get
, Remove
, and other cache operations.
Let's create a console .NET application to explain the use of NCache in Open Source.
Step 1:
Launch Visual Studio 2019+ for .NET Framework.
Step 2:
Create a new Console Application for .NET Framework.
Step 3:
For the NCache Open Source, install the NCache NuGet package through the Package Manager Console as follows:
Install-Package Alachisoft.NCache.OpenSource.SDK
Step 4:
Go to Solutions and select "Add->Class" to create a new class Product as follows:
[Serializable]
public class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public string Category { get; set; }
public int Price { get; set; }
}
Step 5:
Add the following namespaces to your Program.cs file or similar:
using Alachisoft.NCache.Client;
using Alachisoft.NCache.Runtime.Exceptions;
Step 6:
Use the following code in your application's Program.cs or similar class to quickly test NCache.
class Program
{
public static void Main(string[] args)
{
// Set the name of the cache your application needs to talk to
string cacheId = "demoCache";
// Here you get cache handle by initializing cache
ICache cache = CacheManager.GetCache(cacheId);
// Let's create Product class object to be added to the cache
Product product = new Product()
{
ProductID = 1001,
ProductName = "Dell Inspiron",
Category = "Computers",
Price = 600
};
// Create a cache item to be put into the cache.
// You can set expiration, tags etc with cache item. See NCache API reference.
CacheItem cacheItem = new CacheItem(product);
// Cache is a key-value store.
// Every cache item is uniquely identified by its cache key.
string cacheKey = $"Product:{product.ProductID}";
// To put an item into the cache, you can use both Add and Insert methods
cache.Add(cacheKey, cacheItem);
// Let's update the product price
product.Price = 550;
cacheItem.SetValue(product);
// Insert is used to update the existing cache items
cache.Insert(cacheKey, cacheItem);
// Get cache item from cache
product = cache.Get<Product>(cacheKey);
// You can call Remove to remove a cache item from cache
cache.Remove(cacheKey);
}
}
Step 7:
After executing Step 6, compile and run your program to use NCache in your .NET application.
See Also
Create a Cache
Add Local/Remote Clients
Simulate Cache Usage
Monitor Caches in PerfMon
Use NCache for ASP.NET Sessions
NCache Programmer's Guide