.net core, Redis

Connect to a Redis container hosted in Docker from a .NET Core application

Recently I wrote a post on how to install Redis to Windows, and then connect from a .NET Core application. But what about just getting a Redis container from the Docker hub and connecting to that, instead of installing Redis locally?

Step 1: Start a new Redis instance

Open a PowerShell prompt, and run the following command:

docker run -d --name myRedis -p 6379:6379 redis

This simple command creates and runs a container named “myRedis” which is accessible through port 6379.

Step 2: Connect with the connection string “localhost:6379”

In my previous post I stored my Redis connection string in an environment variable. Because this was for a locally installed instance of Redis, I was able to use the connection string of “localhost”. However with the Docker container, my connection string now needs to be “localhost:6379”.

But environment variables are easy to change – now I can open a PowerShell prompt with administrative privileges and update my environment variable:

[Environment]::SetEnvironmentVariable("REDIS_CONNECTIONSTRING", "localhost:6379", "Machine")

Now if I use the C# classes that I wrote about in my previous post (which are on GitHub here), my application will happily connect to the new Redis container, and read and write data to the Redis server.

Wrapping up

This post shows how you can create a local Docker container running Redis, and then connect to it from a .NET application. The benefit here is that you now don’t need to install Redis to your development environment – instead you can a single line of code and have Redis up and running in a few seconds.

.net, Redis

Creating a simple Redis manager in .NET Core (using environment variables to connect)

I’ve been interested in using caching to improve the performance of my .NET applications, and I decided to try out the Redis NoSQL server. This post is about how I started (from a point of knowing nothing about Redis or how to use it), up to the point where I was able to read and write values through a .NET Core application.

Step 1: Installing Redis

I downloaded the latest installer for the Windows version of Redis from here. (You should read the information on this site to determine the if this is best version for you).


This is a fairly simple and straightforward installer – there were a few decision points, such as adding the installation directory to the machine’s path


Also you can choose which port that Redis runs on – 6379 is usually used for non-SSL access, or 6380 for SSL.


This process will also install a Windows service for the Redis database.


Step 2: Create an environment variable to connect to Redis

The simplest connection string is really simple – it’s just “localhost”. So I’ll create an environment variable called “REDIS_CONNECTIONSTRING” with this value. I’ve previously written about this technique.

[Environment]::SetEnvironmentVariable("REDIS_CONNECTIONSTRING", "localhost", "Machine")

Step 3: Create the .NET Core project and class to connect to Redis

First we simply create a new .NET Core project – I’ve called mine RedisAPI.

Once this project is created, I need to add a couple of libraries – the StackExchange.Redis library, and Microsoft.Extensions.Configuration.EnvironmentVariables. I added these in the project.json file using the code below, and restored the packages using “dotnet restore”.

"dependencies": {
  "NETStandard.Library": "1.6.0",
  "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0-rc1-final",
  "StackExchange.Redis": "1.1.608"

The next step is to add a class that connects to the Redis NoSQL instance running on my machine. I found a post from another .NET Engineer, Alwyn Thomas, which creates a RedisConnectionFactory – he explains more about this here. I adjusted his RedisConnectionFactory to pull the Redis connection string from the machine’s environment variables (rather than from application config).

using Microsoft.Extensions.Configuration;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
namespace RedisAPI
    public class RedisConnectionFactory
        private static readonly Lazy<ConnectionMultiplexer> Connection;
        private static readonly string REDIS_CONNECTIONSTRING = "REDIS_CONNECTIONSTRING";
        static RedisConnectionFactory()
            var config = new ConfigurationBuilder()
            var connectionString = config[REDIS_CONNECTIONSTRING];
            if (connectionString == null)
                throw new KeyNotFoundException($"Environment variable for {REDIS_CONNECTIONSTRING} was not found.");
            var options = ConfigurationOptions.Parse(connectionString);
            Connection = new Lazy<ConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(options));
        public static ConnectionMultiplexer GetConnection() => Connection.Value;

Now that I have a connection factory, it’s very simple to create a class which acts as an agent to allow me to read, write and delete string values from the Redis database.

using StackExchange.Redis;
namespace RedisAPI
    public class RedisDataAgent
        private static IDatabase _database;
        public RedisDataAgent()
            var connection = RedisConnectionFactory.GetConnection();
            _database = connection.GetDatabase();
        public string GetStringValue(string key)
            return _database.StringGet(key);
        public void SetStringValue(string key, string value)
            _database.StringSet(key, value);
        public void DeleteStringValue(string key)

Finally I can demonstrate how to use this by creating a console .NET Core app and reference this project – the class below shows how.

using RedisAPI;
namespace ConsoleApp1
    public class Program
        public static void Main(string[] args)
            string inputStringData = "hello world";
            var dataAgent = new RedisDataAgent();
            dataAgent.SetStringValue("cachedVariable", inputStringData);
            // returns "hello world"
            string s = dataAgent.GetStringValue("cachedVariable");

Obviously there is a lot more to Redis than the simple use case I’ve described here – but hopefully this is enough to get started with how to use it to cache data in .NET Core, and configure it using Windows environment variables.