Getting Started - Caching

Different ways for getting started with ServiceStack: Project templates, Walkthroughs, Docs and Videos, choose what's best for you

Setting up a caching provider

By default, a MemoryCacheClient is configured without any additional code in an AppHost. This means the all the features that use ICacheClient will work out of the box with no additional setup.

Configuring to use another implementation requires registering ICacheClient with your applications IoC. These will usually be registered as a factory Func that resolves a single client from a pool.

[assembly: HostingStartup(typeof(MyApp.ConfigureRedis))]

namespace MyApp;

public class ConfigureRedis : IHostingStartup
{
    public void Configure(IWebHostBuilder builder) => builder
        .ConfigureServices(services => {
            services.AddSingleton<IRedisClientsManager>(
                new RedisManagerPool("localhost:6379"));
        })
       .ConfigureAppHost(appHost => {
            // ...
       });
}

Supported Caching Providers

ServiceStack comes with support for multiple Cache Providers out of the box. These include:

  • Memory Cache
  • Redis
  • OrmLiteCacheClient
  • AWS DynamoDb
  • Azure Table Storage
  • Memcached

Each of these options have their own strengths. MemoryCache is useful for single host web services without needing any infrastructure dependencies. Redis is a common choice due to being a fast key-value store with non-volatile persistent storage and support for rich comp-sci data structures.

OrmLiteCacheClient supports all OrmLite’s RDBMS providers for using an existing RDBMS as a distributed cache. Memcached is a tried and tested distributed memory caching provider. AWS DynamoDb and Azure Table Storage give you option to use cloud managed solution that may better suit your use case.

Redis
services.AddSingleton<IRedisClientsManager>(c => 
  new RedisManagerPool("localhost:6379"));
OrmLite
// Register OrmLite Db Factory if not already
services.AddSingleton<IDbConnectionFactory>(c => 
   new OrmLiteConnectionFactory(connString,
       SqlServerDialect.Provider));

// Alternatively, MS SQL Server Optimized cache for improved performance
services.AddSingleton<ICacheClient>(c => 
   new OrmLiteCacheClient<SqlServerMemoryOptimizedCacheEntry>());

// Register DB Cache Client
services.AddSingleton<ICacheClient,OrmLiteCacheClient>();

// Create 'CacheEntry' RDBMS table if doesn't exist
appHost.Resolve<ICacheClient>().InitSchema();

Azure
services.AddSingleton<ICacheClient>(
   new AzureTableCacheClient(cacheConnStr));
Aws
var awsDb = new AmazonDynamoDBClient(
   Secrets.AWS_ACCESS_KEY, 
   Secrets.AWS_SECRET_KEY, 
   RegionEndpoint.USEast1);

services.AddSingleton<IPocoDynamo>(new PocoDynamo(awsDb));
services.AddSingleton<ICacheClient>(c => 
   new DynamoDbCacheClient(c.Resolve<IPocoDynamo>()));

// Create 'CacheEntry' DynamoDB table if doesn't exist
appHost.Resolve<ICacheClient>().InitSchema();