How to connect to Redis in a C# .NET project using the NRedisStack client library
Last updated 20, Apr 2024
Goal
Understand how to connect to Redis using the NRedisStack client library for the C# programming language for the .NET platform.
Solution
The following example demonstrates how to create a scaffold project to connect Redis with the NRedisStack client library for the .NET programming language. To start with the example, download the .NET platform.
https://dotnet.microsoft.com/en-us/download/dotnet
Proceed to install and verify that the required version is correctly installed.
dotnet --info
You can now create a new project from scratch (assuming .NET version 8 is installed).
dotnet new console -o redis-test -f net8.0
Install the NRedisStack package, which is required by the example discussed in this document. Choose the desired version.
cd redis-test
dotnet add package NRedisStack --version 0.12.0
Now edit the Program.cs file in the project folder and paste this content:
using NRedisStack;
using StackExchange.Redis;
ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
IDatabase db = redis.GetDatabase();
db.StringSet("foo", "bar");
Console.WriteLine(db.StringGet("foo"));
You can now execute this program as follows:
dotnet run