Migrating to AWS: Using the AWS SDK for .NET in Enterprise Projects

Hands-On Examples: S3, DynamoDB, and Lambda with the AWS SDK for .NET

This guide shows concise, practical examples for using AWS services from a .NET application with the AWS SDK for .NET (AWSSDK). It assumes .NET 6+ and the AWSSDK NuGet packages. Each example includes setup, code snippets, and key tips.

Prerequisites

  • .NET 6+ SDK installed.
  • AWS credentials configured (e.g., ~/.aws/credentials, environment variables, or AWS IAM role).
  • Install packages (examples):

Code

dotnet add package AWSSDK.S3 dotnet add package AWSSDK.DynamoDBv2 dotnet add package AWSSDK.Lambda

1) Amazon S3 — Upload and Download a File

  • Use AmazonS3Client from Amazon.S3.
  • Upload:

csharp

using Amazon.S3; using Amazon.S3.Transfer; var s3Client = new AmazonS3Client(region: Amazon.RegionEndpoint.USEast1); var transferUtility = new TransferUtility(s3Client); await transferUtility.UploadAsync(“local-file.txt”, “my-bucket”, “folder/local-file.txt”);
  • Download:

csharp

await transferUtility.DownloadAsync(“downloaded.txt”, “my-bucket”, “folder/local-file.txt”);
  • Tips: use TransferUtility for large files, enable server-side encryption by setting PutObjectRequest.ServerSideEncryption, set ACLs carefully, and use presigned URLs for temporary access.

2) Amazon DynamoDB — Basic CRUD

  • Use AmazonDynamoDBClient and DynamoDBContext (Object Persistence Model).
  • Define a model:

csharp

using Amazon.DynamoDBv2.DataModel; [DynamoDBTable(“Users”)] public class User { [DynamoDBHashKey] public string UserId { get; set; } [DynamoDBProperty] public string Name { get; set; } [DynamoDBProperty] public int Age { get; set; } }
  • Save (Create/Update):

csharp

var client = new AmazonDynamoDBClient(); var context = new DynamoDBContext(client); await context.SaveAsync(new User { UserId = “u123”, Name = “Alex”, Age = 30 });
  • Read:

csharp

var user = await context.LoadAsync<User>(“u123”);
  • Delete:

csharp

await context.DeleteAsync<User>(“u123”);
  • Query/Scan: prefer Query with a proper key design for performance; use AsyncSearch for paginated results.
  • Tips: design partition/sort keys for access patterns, use batch operations for throughput, enable adaptive capacity and auto-scaling for production.

3) AWS Lambda — Invoke Function and Local Testing

  • Use AmazonLambdaClient to invoke functions.
  • Invoke synchronous:

csharp

using Amazon.Lambda; using Amazon.Lambda.Model; var lambda = new AmazonLambdaClient(); var payload = ”{“name”:“Alex”}”; var response = await lambda.InvokeAsync(new InvokeRequest { FunctionName = “MyFunction”, Payload = payload, InvocationType = InvocationType.RequestResponse }); using var sr = new StreamReader(response.Payload); var result = await sr.ReadToEndAsync();
  • Invoke asynchronously by setting InvocationType.Event.
  • Local testing: use AWS SAM CLI or .NET Lambda Test Tool to run and debug functions locally.
  • Deployment: use Amazon.Lambda.Tools (dotnet lambda deploy-function) or CI pipelines (SAM/CDK).
  • Tips: keep Lambda handlers small, use dependency injection with Amazon.Lambda.AspNetCoreServer for web apps, and set proper memory/timeout.

4) Cross-cutting concerns & best practices

  • Credential handling: prefer IAM roles for EC2/ECS/Lambda; avoid hardcoding keys.
  • Async/await: use asynchronous APIs to avoid thread blocking.
  • Retry & backoff: rely on SDK default retry or configure exponential backoff for transient errors.
  • Logging & monitoring: integrate CloudWatch, X-Ray tracing, and structured logs.
  • Security: least-privilege IAM policies, encrypt sensitive data, rotate keys if any.
  • Performance: reuse client instances (they are thread-safe), tune HTTP connection settings, and use paginated APIs efficiently.

5) Quick sample project layout

  • Console app or ASP.NET Core service
    • Services/S3Service.cs
    • Services/DynamoDbService.cs
    • Services/LambdaService.cs
    • Models/
    • Program.cs (DI registration)
  • Include integration tests using LocalStack or AWS SAM for safe testing.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *