All eyes on AI: 2026 predictions – The shifts that will shape your stack.

Read now

Tutorial

.NET and Redis

February 24, 20263 minute read
Steve Lorello
Steve Lorello
To use Redis with .NET, install the StackExchange.Redis NuGet package, create a ConnectionMultiplexer, and call commands like StringSet and StringGet on the IDatabase object. StackExchange.Redis is the most widely adopted C# Redis client, built by the team behind StackOverflow.

#What you'll learn

  • How to install the StackExchange.Redis NuGet package
  • How to connect to Redis from a .NET application using ConnectionMultiplexer
  • How to perform basic CRUD operations (strings, lists, sets, hashes)
  • Best practices for managing Redis connections in production

#Prerequisites

  • .NET 6+ SDK (or .NET Core 3.1+)
  • A running Redis instance — start one locally with Docker (docker run -p 6379:6379 redis) or use Redis Cloud
  • An IDE such as Visual Studio, Rider, or VS Code

#How do I install StackExchange.Redis?

There are several ways to add the package to your project.

#.NET CLI

Run the following in the directory of the .csproj file you want to add the package to:

#Package Manager Console

Run the following command from the Package Manager Console:

#Package Reference

You can also add the package directly to your .csproj file:

#NuGet GUI

If you're using Visual Studio and prefer a graphical interface, follow the steps outlined by Microsoft and search for StackExchange.Redis.

#How do I connect to Redis from .NET?

First, import the namespace:
Then initialize the ConnectionMultiplexer. This is the central object for communicating with Redis. Your application should maintain a single instance throughout its lifetime — it is thread-safe and designed to be reused.
A typical connection string follows the format HOST:PORT,password=PASSWORD:
Once you have a multiplexer, get a reference to the database:

#ConnectionMultiplexer best practices

  • Create one ConnectionMultiplexer and reuse it for the lifetime of the application.
  • Register for the ConnectionFailed and ConnectionRestored events to monitor connectivity.
  • In ASP.NET Core, register the multiplexer as a singleton in the dependency injection container.

#How do I perform CRUD operations with C# and Redis?

#Ping the database

#String operations — get and set

Set a string value:
Get a string value:

#List operations

Push to a list:
Pop from a list:

#Set operations

Add members to sets:
Compute the union of two sets:

#Hash operations

Add fields to a hash:
Get a single field:
Get all fields:

#Sample .NET and Redis applications

Rate-limiting example app built with .NET and StackExchange.Redis

Leaderboard example app using Redis sorted sets in .NET
API caching example with ASP.NET Core and Redis

Basic chat app using Redis Pub/Sub in .NET

#Next steps

Now that you have StackExchange.Redis set up, explore more advanced .NET and Redis topics: