using KBR.Cache.Constants; using KBR.Cache.Options; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using System.Diagnostics.CodeAnalysis; namespace KBR.Cache.Extensions { public static class ServiceCollectionExtensions { public static IServiceCollection AddCache([NotNull] this IServiceCollection services, IConfiguration configuration) { // Ensure the 'Microsoft.Extensions.Options.ConfigurationExtensions' package is referenced in your project var cacheOptions = configuration.GetSection("Cache").Get(); if (cacheOptions == null || cacheOptions.Provider == CacheProviders.InMemory) { services.AddDistributedMemoryCache(); } else if (cacheOptions.Provider == CacheProviders.SqlServer) { services.AddDistributedMySqlCache(options => { options.ConnectionString = cacheOptions.ConnectionString; options.TableName = "Cache"; }); } else if (cacheOptions.Provider == CacheProviders.Redis) { services.AddStackExchangeRedisCache(options => { options.Configuration = cacheOptions.ConnectionString; options.InstanceName = "SampleInstance"; }); } else { throw new Exception("Cache options are not valid"); } services.TryAddSingleton(); return services; } } }