---
slug: getting-started
title: Getting Started with Redis in .NET
---
## Introduction to Redis as a Technology
Redis, standing for REmote DIctionary Server, is an open-source, in-memory data structure store. It's widely used as a database, cache, and message broker. With its unique set of features and unparalleled speed, it's a crucial tool for a modern developer's toolkit.
## Key Features of Redis
Redis supports various kinds of data structures like [strings](https://redis.io/docs/data-types/strings), [hashes](https://redis.io/docs/data-types/hashes), [lists](https://redis.io/docs/data-types/lists), [sets](https://redis.io/docs/data-types/sets), [sorted sets with range queries](https://redis.io/docs/data-types/sorted-sets), [bitmaps](https://redis.io/docs/data-types/bitmaps), [hyperloglogs](https://redis.io/docs/data-types/hyperloglogs), and geospatial indexes with [radius queries](https://redis.io/docs/data-types/geospatial). This wide array of data types and its ability to perform [atomic operations](https://redis.io/docs/manual/transactions/) make Redis extremely versatile for solving a myriad of problems.

## High Performance and Speed
This support for a wide array of fundamental computational storage data structures is what sets Redis apart, and enables [blazing speed](https://redis.io/topics/benchmarks) when applied correctly. As an in-memory data store, reading and writing data happens exceedingly fast. This makes Redis an excellent choice for applications that require real-time data processing.

## Durability and Persistence
Even though Redis is an in-memory data store, it provides mechanisms to achieve data [persistence](https://redis.io/topics/persistence). You have the flexibility to choose from options like [snapshotting](https://redis.io/docs/management/persistence/#snapshotting) and append-only files (AOF), depending on your application's needs.
## Scalability and High Availability
Redis has robust features like [replication](https://redis.io/topics/replication), [Lua scripting](https://redis.io/commands/eval), [transactions](https://redis.io/docs/manual/transactions), and different levels of [on-disk persistence](https://redis.io/topics/persistence). With the help of [Redis Sentinel](https://redis.io/topics/sentinel), it provides high availability via automatic partitioning across multiple Redis nodes. It is also widely supported on major cloud providers as a managed service, like on [AWS under the ElastiCache product](https://aws.amazon.com/elasticache/redis/).

## Extensible and Versatile
You can extend Redis functionality using Redis modules. It's also a good fit for job & queue management, caching, real-time analytics, and many other use-cases.
Before we dive into using the ServiceStack.Redis .NET client, we will need a locally running Redis server. The easiest way to get this working is by using the [official Redis Docker image](https://hub.docker.com/_/redis), and using [Docker Desktop](https://www.docker.com/products/docker-desktop) to run it.
## Setting Up a Local Redis Server with Docker
To follow along with this tutorial, you will need a running instance of Redis. One of the easiest ways to get this set up is through Docker, which allows you to run a Redis server within a container on your machine.
If you do not have Docker installed, you can download it from the [official Docker website](https://www.docker.com/products/docker-desktop).
Once you have Docker installed and running, you can set up a Redis instance with the following command:
```bash
docker run --name local-redis -p 6379:6379 -d redis
```
This command tells Docker to run a container with the name "local-redis", using the official Redis image from Docker Hub. The `-p` flag maps the default Redis port (6379) from the container to your local machine, and the `-d` flag tells Docker to run the container in the background.
To confirm that your Redis server is running correctly, you can use the following command:
```bash
docker ps
```
This command lists all running Docker containers. If everything is set up correctly, you should see your "local-redis" container in the list.
Now, your local Redis server is running and ready to be connected on `localhost:6379`.
For more detailed information about Docker commands, you can refer to the [official Docker documentation](https://docs.docker.com/engine/reference/commandline/cli/).
## Using the redis-cli from Docker
Another way to validate your local Redis Docker container is running and access it is by using the Redis-CLI.
If you don't have the Redis-CLI, we can actually use it from the same `redis` Docker image using the following command.
```bash
docker run -it redis /bin/bash -c "redis-cli -h host.docker.internal"
```
> `host.docker.internal` is a way of accessing the Docker host containers, however it may only work on Windows & macOS.
## Installing and Setting Up ServiceStack.Redis in Your Project
Now that we have our local Redis server set up and running, let's move on to adding ServiceStack.Redis to your .NET project. Here we will demonstrate this process in a .NET Console application for simplicity.
To start with, make sure you have the [.NET SDK](https://dotnet.microsoft.com/download) installed on your system. Once you have the SDK, you can create a new Console application with the following command:
```bash
dotnet new console -n RedisConsoleApp
```
After creating your Console application, navigate to the project directory:
```bash
cd RedisConsoleApp
```
Then, add the ServiceStack.Redis NuGet package:
```bash
dotnet add package ServiceStack.Redis
```
Now you have successfully added the ServiceStack.Redis library to your project. In your `Program.cs`, you can import the library using:
```csharp
using ServiceStack.Redis;
```
You are now set to start using Redis in your .NET console application.
### Using the ServiceStack `x` tool
For developers working on larger projects or who want a quicker setup, ServiceStack provides a .NET tool called `x`. You can install this tool using the following command:
```bash
dotnet tool install --global x
```
This tool allows you to create new projects and add (mix in) functionality quickly and easily. To create a new web project, you can use the following command:
```bash
npx create-net web ProjectName
```
To add Redis support to your project, navigate to your project directory and then use the `mix` command:
```bash
cd ProjectName
npx add-in redis
```
This automatically adds the ServiceStack.Redis library to your project and sets up a basic Redis configuration.
For further information on using the `x` tool, refer to the [ServiceStack `x` tool documentation](/dotnet-tool).
## Connecting and Using Redis Client Managers
In the previous section, we installed and set up the ServiceStack.Redis library in our .NET Console application. Now, let's learn how to use the Redis Client Managers provided by this library to interact with Redis.
ServiceStack.Redis provides a few different client managers, but for this tutorial, we will use `RedisManagerPool`. This client manager is a simple and efficient pool of Redis clients that is suitable for most use cases.
### Connecting to Redis
To start, you will first need to establish a connection to your Redis server. You can do this by passing your Redis server's connection string to the `RedisManagerPool` constructor:
```csharp
var manager = new RedisManagerPool("localhost:6379");
```
Now that you have a manager, you can get a Redis client instance from it:
```csharp
using (var redis = manager.GetClient())
{
// You can now use `redis` to interact with your Redis server.
}
```
### Using the Client with .NET Core Dependency Injection
If you are building a web application with .NET Core, you might want to make use of .NET Core's built-in dependency injection (DI) to manage your Redis clients. Here is how you can register your `RedisManagerPool` with the DI container:
```csharp
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton(new RedisManagerPool("localhost:6379"));
// Add other services...
}
```
Now, the DI container will manage the lifecycle of the `RedisManagerPool`, and you can inject [`IRedisClientsManager`](https://reference.servicestack.net/api/ServiceStack.Redis/IRedisClientsManager/) into your services:
```csharp
public class MyService : Service
{
public IRedisClientsManager RedisClientsManager { get; set; }
public void Any(Request request)
{
using (var redis = RedisClientsManager.GetClient())
{
// Use `redis` to interact with your Redis server.
}
}
}
```
If you are using ServiceStack, you can simply use the `base.Redis` property from the `Service` base class to resolve a Redis client:
```csharp
public class MyService : Service
{
public void Any(Request request)
{
var redis = base.Redis;
// Use `redis` to interact with your Redis server.
}
}
```
## Leveraging the Simplicity of ICacheClient
ServiceStack's `ICacheClient` is an abstraction over caching operations, which allows you to interact with various cache implementations in a standard way. Once `IRedisClientsManager` is registered in the IoC container, ServiceStack switches the implementation of `ICacheClient` to use Redis as its backend.
In ServiceStack services, you can easily access the cache via the `base.Cache` property of the `Service` base class. Here is an example of how you can use the `Get` and `Set` methods to work with Redis cache:
```csharp
public class MyService : Service
{
public object Any(Request request)
{
var cacheKey = "unique-cache-key";
var existingValue = base.Cache.Get(cacheKey);
if (existingValue == null)
{
existingValue = "This is a value from some expensive operation";
base.Cache.Set(cacheKey, existingValue);
}
return new { Value = existingValue };
}
}
```
This example checks if a value is available in the cache. If the value is not present, it performs an expensive operation to get the value (in this case, we're just setting a string), then stores the value in the cache for subsequent requests.
The `ICacheClient` interface also supports asynchronous operations. If you want to use the async versions of these methods, you can use the `base.CacheAsync` property of the `Service` base class:
```csharp
public class MyService : Service
{
public async Task