Skip to content

Instantly share code, notes, and snippets.

@AndyButland
Created May 21, 2023 11:55
Show Gist options
  • Save AndyButland/a47e8632f025d6252ec8d5e5e83330fe to your computer and use it in GitHub Desktop.
Save AndyButland/a47e8632f025d6252ec8d5e5e83330fe to your computer and use it in GitHub Desktop.
public class Startup
{
public Startup(IConfiguration configuration) => Configuration = configuration;
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
IConfigurationSection apiSettingsSection = Configuration.GetSection(Constants.ConfigurationKeys.ApiSettingsKeyName);
services.Configure<ApiSettings>(apiSettingsSection);
DistributedCacheMethodOption distributedCacheMethod = apiSettingsSection.GetValue<DistributedCacheMethodOption>(nameof(ApiSettings.DistributedCacheMethod));
services.AddDistributedCache(Configuration, distributedCacheMethod);
}
}
public static class ServiceCollectionExtension
{
public static IServiceCollection AddDistributedCache(this IServiceCollection services, IConfiguration configuration, DistributedCacheMethodOption distributedCacheMethodOption)
{
switch (distributedCacheMethodOption)
{
case DistributedCacheMethodOption.InMemory:
services.AddDistributedMemoryCache();
break;
case DistributedCacheMethodOption.Redis:
services.AddStackExchangeRedisCache(options => {
options.Configuration = configuration[Constants.ConfigurationKeys.RedisConnectionStringKeyName];
options.InstanceName = Constants.DistributedCache.InstanceName;
});
break;
default:
throw new ArgumentOutOfRangeException(nameof(distributedCacheMethodOption));
}
return services;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment