### Install NuGet Package Source: https://github.com/aws/aws-secretsmanager-caching-net/blob/master/README.md Add the caching client dependency to your .NET project via NuGet. ```xml ``` -------------------------------- ### Install Secrets Manager Caching NuGet Package Source: https://context7.com/aws/aws-secretsmanager-caching-net/llms.txt Add the AWSSDK.SecretsManager.Caching NuGet package to your .NET project. ```xml ``` -------------------------------- ### Access SecretCacheItem Directly Source: https://context7.com/aws/aws-secretsmanager-caching-net/llms.txt Access the underlying SecretCacheItem for advanced scenarios requiring direct cache manipulation. Use this to get the secret value or force a refresh of a specific cache item. ```csharp using Amazon.SecretsManager.Extensions.Caching; public class AdvancedCacheUsage { private readonly SecretsManagerCache _cache = new SecretsManagerCache(); public async Task DemonstrateDirectCacheAccessAsync() { string secretId = "prod/api/credentials"; // Get the cache item directly SecretCacheItem cacheItem = _cache.GetCachedSecret(secretId); // The cache item can be used to get the secret value var response = await cacheItem.GetSecretValue(CancellationToken.None); if (response != null) { Console.WriteLine($"Secret Name: {response.Name}"); Console.WriteLine($"Version ID: {response.VersionId}"); Console.WriteLine($"Has String: {response.SecretString != null}"); Console.WriteLine($"Has Binary: {response.SecretBinary != null}"); } // Force refresh the specific cache item bool refreshed = await cacheItem.RefreshNowAsync(); Console.WriteLine($"Refresh successful: {refreshed}"); } } ``` -------------------------------- ### Initialize and Use SecretsManagerCache Source: https://github.com/aws/aws-secretsmanager-caching-net/blob/master/README.md Instantiate the cache and retrieve a secret string within a .NET application. ```csharp using System; using Amazon.SecretsManager.Extensions.Caching.SecretsManagerCache; namespace LambdaExample { public class CachingExample { private SecretsManagerCache cache = new SecretsManagerCache(); private const String MySecretName = "MySecret"; public async Task FunctionHandlerAsync(String input, ILambdaContext context) { String MySecret = await cache.GetSecretString(MySecretName); ... } } } ``` -------------------------------- ### Create SecretsManagerCache Instance Source: https://context7.com/aws/aws-secretsmanager-caching-net/llms.txt Instantiate SecretsManagerCache with default or custom configurations, including a custom Secrets Manager client and cache settings like TTL and max cache size. ```csharp using Amazon.SecretsManager; using Amazon.SecretsManager.Extensions.Caching; // Default constructor - creates cache with default client and configuration var cache = new SecretsManagerCache(); ``` ```csharp var client = new AmazonSecretsManagerClient(Amazon.RegionEndpoint.USWest2); var cacheWithClient = new SecretsManagerCache(client); ``` ```csharp var config = new SecretCacheConfiguration { CacheItemTTL = 1800000, // 30 minutes in milliseconds MaxCacheSize = 500 }; var cacheWithConfig = new SecretsManagerCache(config); ``` ```csharp var fullCustomCache = new SecretsManagerCache(client, config); ``` -------------------------------- ### Configure Cache Behavior with SecretCacheConfiguration Source: https://context7.com/aws/aws-secretsmanager-caching-net/llms.txt Define cache settings such as TTL, maximum size, and version stages using the SecretCacheConfiguration object. ```csharp using Amazon.SecretsManager; using Amazon.SecretsManager.Extensions.Caching; // Full configuration example var config = new SecretCacheConfiguration { // Cache item TTL in milliseconds (default: 3600000 = 1 hour) CacheItemTTL = 1800000, // 30 minutes // Maximum number of secrets to cache before LRU eviction (default: 1024) MaxCacheSize = 500, // Version stage to retrieve (default: "AWSCURRENT") VersionStage = "AWSCURRENT", // Optional: Custom Secrets Manager client Client = new AmazonSecretsManagerClient(Amazon.RegionEndpoint.EUWest1), // Optional: Cache hook for custom processing CacheHook = null }; var cache = new SecretsManagerCache(config); // Example: Short-lived cache for frequently rotating secrets var shortLivedConfig = new SecretCacheConfiguration { CacheItemTTL = 60000, // 1 minute MaxCacheSize = 100 }; var shortLivedCache = new SecretsManagerCache(shortLivedConfig); // Example: Retrieve pending version during rotation var pendingConfig = new SecretCacheConfiguration { VersionStage = "AWSPENDING" }; var pendingCache = new SecretsManagerCache(pendingConfig); ``` -------------------------------- ### Retrieve Binary Secrets with Caching Source: https://context7.com/aws/aws-secretsmanager-caching-net/llms.txt Asynchronously retrieve binary secret values from the cache. Handles non-text data like encryption keys or certificates. ```csharp using Amazon.SecretsManager.Extensions.Caching; public class EncryptionKeyService { private readonly SecretsManagerCache _cache = new SecretsManagerCache(); public async Task GetEncryptionKeyAsync() { // Retrieve binary secret byte[] encryptionKey = await _cache.GetSecretBinary("prod/encryption/master-key"); if (encryptionKey == null) { throw new InvalidOperationException("Encryption key not found or is stored as string"); } return encryptionKey; } public async Task GetCertificateAsync(CancellationToken cancellationToken) { return await _cache.GetSecretBinary("prod/certificates/ssl-cert", cancellationToken); } } ``` -------------------------------- ### Implement Custom Cache Processing with ISecretCacheHook Source: https://context7.com/aws/aws-secretsmanager-caching-net/llms.txt Implement the ISecretCacheHook interface to perform custom operations like encryption or transformation when secrets are stored or retrieved from the cache. ```csharp using Amazon.SecretsManager.Extensions.Caching; using System.Security.Cryptography; using System.Text; public class EncryptedCacheHook : ISecretCacheHook { private readonly byte[] _encryptionKey; public EncryptedCacheHook(byte[] encryptionKey) { _encryptionKey = encryptionKey; } // Called when storing secret in cache - encrypt the data public object Put(object o) { // Encrypt the object before storing in memory string json = System.Text.Json.JsonSerializer.Serialize(o); byte[] encrypted = EncryptData(Encoding.UTF8.GetBytes(json)); return encrypted; } // Called when retrieving secret from cache - decrypt the data public object Get(object cachedObject) { byte[] encrypted = (byte[])cachedObject; byte[] decrypted = DecryptData(encrypted); string json = Encoding.UTF8.GetString(decrypted); return System.Text.Json.JsonSerializer.Deserialize(json); } private byte[] EncryptData(byte[] data) { /* encryption logic */ return data; } private byte[] DecryptData(byte[] data) { /* decryption logic */ return data; } } // Usage var hook = new EncryptedCacheHook(myEncryptionKey); var config = new SecretCacheConfiguration { CacheHook = hook }; var cache = new SecretsManagerCache(config); ``` -------------------------------- ### Force Cache Refresh with RefreshNowAsync Source: https://context7.com/aws/aws-secretsmanager-caching-net/llms.txt Use RefreshNowAsync to bypass TTL and force an immediate update of a cached secret. This is useful after receiving a rotation notification. ```csharp using Amazon.SecretsManager.Extensions.Caching; public class SecretRotationHandler { private readonly SecretsManagerCache _cache = new SecretsManagerCache(); public async Task HandleSecretRotationAsync(string secretId) { // Get current cached value string oldValue = await _cache.GetSecretString(secretId); Console.WriteLine($"Current cached value: {oldValue}"); // Force refresh after rotation notification bool refreshSuccess = await _cache.RefreshNowAsync(secretId); if (refreshSuccess) { string newValue = await _cache.GetSecretString(secretId); Console.WriteLine($"Refreshed value: {newValue}"); } else { Console.WriteLine("Refresh failed - continuing with cached value"); } } // With cancellation token public async Task RefreshWithTimeoutAsync(string secretId, CancellationToken cancellationToken) { return await _cache.RefreshNowAsync(secretId, cancellationToken); } } ``` -------------------------------- ### Retrieve String Secrets with Caching Source: https://context7.com/aws/aws-secretsmanager-caching-net/llms.txt Asynchronously retrieve a secret string from the cache. Subsequent calls for the same secret within the TTL will return the cached value. ```csharp using Amazon.SecretsManager.Extensions.Caching; public class DatabaseConnectionService { private readonly SecretsManagerCache _cache = new SecretsManagerCache(); public async Task GetDatabaseConnectionStringAsync() { // Retrieve secret by name or ARN string connectionString = await _cache.GetSecretString("prod/database/connection"); // Subsequent calls return cached value until TTL expires string cachedValue = await _cache.GetSecretString("prod/database/connection"); return connectionString; } // With cancellation token support public async Task GetSecretWithCancellationAsync(CancellationToken cancellationToken) { return await _cache.GetSecretString("prod/api/key", cancellationToken); } } ``` -------------------------------- ### Integrate SecretsManagerCache in AWS Lambda Source: https://context7.com/aws/aws-secretsmanager-caching-net/llms.txt Utilize a static cache instance to persist secrets across warm Lambda invocations. Configure the TTL to balance secret freshness and API call frequency. ```csharp using Amazon.Lambda.Core; using Amazon.SecretsManager.Extensions.Caching; using System.Text.Json; [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace LambdaExample { public class Function { // Cache instance persists across Lambda invocations (warm start) private static readonly SecretsManagerCache Cache = new SecretsManagerCache( new SecretCacheConfiguration { CacheItemTTL = 300000 } // 5 minutes ); private const string DbSecretName = "prod/database/credentials"; public async Task FunctionHandler( APIGatewayProxyRequest request, ILambdaContext context) { try { // Retrieve database credentials from cache string secretJson = await Cache.GetSecretString(DbSecretName); var credentials = JsonSerializer.Deserialize(secretJson); // Use credentials to connect to database using var connection = CreateConnection(credentials); var result = await ExecuteQuery(connection, request); return new APIGatewayProxyResponse { StatusCode = 200, Body = JsonSerializer.Serialize(result) }; } catch (Exception ex) { context.Logger.LogError($"Error: {ex.Message}"); return new APIGatewayProxyResponse { StatusCode = 500 }; } } private record DatabaseCredentials(string Host, string Username, string Password, int Port); } } ``` -------------------------------- ### Dispose Secrets Manager Cache Source: https://context7.com/aws/aws-secretsmanager-caching-net/llms.txt Properly dispose of the cache when it's no longer needed to release memory resources. The using statement pattern ensures automatic disposal. ```csharp using Amazon.SecretsManager.Extensions.Caching; public class DisposableCacheExample : IDisposable { private readonly SecretsManagerCache _cache; public DisposableCacheExample() { _cache = new SecretsManagerCache(); } public async Task GetSecretAsync(string secretId) { return await _cache.GetSecretString(secretId); } public void Dispose() { _cache.Dispose(); } } // Using statement pattern public async Task UseWithDisposalAsync() { using var cache = new SecretsManagerCache(); string secret = await cache.GetSecretString("my-secret"); // Cache is automatically disposed when scope exits } ``` -------------------------------- ### Implement Resilient Secret Retrieval Source: https://context7.com/aws/aws-secretsmanager-caching-net/llms.txt Handle specific AmazonServiceException types to differentiate between missing secrets, access issues, and transient network errors. The cache automatically manages exponential backoff for retries. ```csharp using Amazon.SecretsManager.Extensions.Caching; using Amazon.Runtime; public class ResilientSecretService { private readonly SecretsManagerCache _cache; public ResilientSecretService() { _cache = new SecretsManagerCache(new SecretCacheConfiguration { CacheItemTTL = 3600000 // 1 hour }); } public async Task GetSecretWithFallbackAsync(string secretId) { try { return await _cache.GetSecretString(secretId); } catch (AmazonServiceException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound) { // Secret doesn't exist throw new SecretNotFoundException($"Secret '{secretId}' not found", ex); } catch (AmazonServiceException ex) when (ex.StatusCode == System.Net.HttpStatusCode.Forbidden) { // Access denied - check IAM permissions throw new SecretAccessDeniedException($"Access denied to secret '{secretId}'", ex); } catch (AmazonClientException ex) { // Network or client-side error - cache will automatically retry with backoff // On subsequent calls within backoff period, cached exception is thrown throw new SecretRetrievalException($"Failed to retrieve secret '{secretId}'", ex); } } public async Task GetSecretOrDefaultAsync(string secretId, string defaultValue) { try { string value = await _cache.GetSecretString(secretId); return value ?? defaultValue; } catch (AmazonServiceException) { return defaultValue; } } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.