In the second blog post series “Redis for .NET Developer” I will show how we will use C# to connect to Redis.
If you want to learn how to install Redis, visit my previous post on Intro to Redis for .NET Developers – Installing Redis on Windows.
We will be using StackExchange.Redis library to connect to Redis. One can download StackExchange. Redis through NuGet.

Dotnetcore Sample
I have added sample code for Dotnet Core also below
StackExchange.Redis is a high performance general purpose redis client for .NET languages (C# etc).

For .NET Framework

1. Let’s Download our Nuget package, you can use the command line like below or use Visual Studio (I am using VS2018).

Search for redis in your nuget window.

Nuget Redis

Once installed you will see in your output windows.

Nuget Redis Result

Now that the nuget package is installed, we can build a C# console app that will connect to your redis server.
Below is a sample code to connect to localhost of your redis.

The above code will allow you to connect to Redis and store a string key “testKey” with a value of “testValue”.

For better modulation of Redis it is recommended to store ConnectionMultiplexer as a static singleton in your application.

Below is example of a RedisStore that stores the ConnectionMultiplexer as a static Lazy loaded singleton.

Now our previous code would something like

Dotnet Core Version for Connection

Lets go through the process of creating a dotnet core console application.

We will now need to install all the packages that we require to run dotnetcore with Redis.

We will create an appsettings.json file to store our connection information, that is one of the reason we have installed all those packages into our project.

I am running Redis on my localhost on Docker

This is how my appsettings.json looks like, with only one key and value.

We also need to tell our csproj about the output of the json file by modifying our RedisConnectionDotNetCore.csproj, we will add into our ItemGroup

Lets modify our code in RedisStore.cs such that it can read from the json file, as you can see most of the code remains the same except for where we pick our configuration from.

Our Program.cs remains the same

Now we can run with dotnet command line

In my next blog post I will cover the data structures that Redis provides.

For code please visit https://github.com/taswar/RedisForNetDevelopers

For previous Redis topics

  1. Intro to Redis for .NET Developers