### 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