Using Memcached with a .NET Console Application

A little while ago I wrote a post about using Memcached with AWS Lambda functions. While working on that post, I used a Memcached Docker container on my laptop to work on the code. Starting the container was easy, but getting the .NET Memcached client instantiated was a little more difficult than I expected.

Most of the online examples assume you are using a Web API or MVC application that has logging and dependency injection by default.

It took a bit of trial and error, but I got it working, so this post might save you half an hour of messing around.

The Docker Container

You need to have Docker installed and running.

Then from the command line run -

docker run --rm -it -p 11211:11211 memcached

You will see some output from Docker if it needs to download the image, otherwise, you will see no output.

The .NET Client

Create a new .NET Console application.

Add two NuGet packages - EnyimMemcachedCore and Microsoft.Extensions.Logging.Console.

Open the Program.cs file and replace its content with -

using Enyim.Caching;
using Enyim.Caching.Configuration;
using Microsoft.Extensions.Logging;

string key = "MyKey";

using var loggerFactory = LoggerFactory.Create(builder => 
    builder.AddConsole()
    .SetMinimumLevel(LogLevel.Warning)); 

ILogger logger = loggerFactory.CreateLogger<Program>();

var config = new MemcachedClientConfiguration(loggerFactory, new MemcachedClientOptions());
config.AddServer("localhost", 11211);

MemcachedClient myCache = new MemcachedClient(loggerFactory, config);

Console.WriteLine($"Setting - Key:{key}, Value:999");
await myCache.SetAsync(key, 999, 10);

Console.WriteLine($"\nWaiting a second...\n");
await Task.Delay(1000);

int number = myCache.Get<int>(key);
Console.WriteLine($"Getting - Key:{key}, Value:{number}");

Run the application and you will see the following output -

Setting - Key:MyKey, Value:999

Waiting a second...

Getting - Key:MyKey, Value:999

That’s it. Very simple.

comments powered by Disqus

Related