Skip to content

Commit 2f452d3

Browse files
committed
Update wrapper and scenario.
1 parent 2e74418 commit 2f452d3

4 files changed

Lines changed: 79 additions & 54 deletions

File tree

dotnetv4/DynamoDB/Actions/DynamoDbMethods.cs renamed to dotnetv4/DynamoDB/Actions/DynamoDbWrapper.cs

Lines changed: 36 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,21 @@
99

1010
namespace DynamoDBActions;
1111

12-
public class DynamoDbMethods
12+
/// <summary>
13+
/// Methods of this class perform Amazon DynamoDB operations.
14+
/// </summary>
15+
public class DynamoDbWrapper
1316
{
17+
private readonly IAmazonDynamoDB _amazonDynamoDB;
18+
19+
/// <summary>
20+
/// Constructor for the DynamoDbWrapper class.
21+
/// </summary>
22+
/// <param name="amazonDynamoDB">The injected DynamoDB client.</param>
23+
public DynamoDbWrapper(IAmazonDynamoDB amazonDynamoDB)
24+
{
25+
_amazonDynamoDB = amazonDynamoDB;
26+
}
1427
// snippet-start:[DynamoDB.dotnetv4.dynamodb-basics.CreateTable]
1528

1629
/// <summary>
@@ -20,11 +33,11 @@ public class DynamoDbMethods
2033
/// <param name="client">An initialized Amazon DynamoDB client object.</param>
2134
/// <param name="tableName">The name of the table to create.</param>
2235
/// <returns>A Boolean value indicating the success of the operation.</returns>
23-
public static async Task<bool> CreateMovieTableAsync(AmazonDynamoDBClient client, string tableName)
36+
public async Task<bool> CreateMovieTableAsync(string tableName)
2437
{
2538
try
2639
{
27-
var response = await client.CreateTableAsync(new CreateTableRequest
40+
var response = await _amazonDynamoDB.CreateTableAsync(new CreateTableRequest
2841
{
2942
TableName = tableName,
3043
AttributeDefinitions = new List<AttributeDefinition>()
@@ -72,7 +85,7 @@ public static async Task<bool> CreateMovieTableAsync(AmazonDynamoDBClient client
7285
{
7386
Thread.Sleep(sleepDuration);
7487

75-
var describeTableResponse = await client.DescribeTableAsync(request);
88+
var describeTableResponse = await _amazonDynamoDB.DescribeTableAsync(request);
7689
status = describeTableResponse.Table.TableStatus;
7790

7891
Console.Write(".");
@@ -110,7 +123,7 @@ public static async Task<bool> CreateMovieTableAsync(AmazonDynamoDBClient client
110123
/// the movie to add to the table.</param>
111124
/// <param name="tableName">The name of the table where the item will be added.</param>
112125
/// <returns>A Boolean value that indicates the results of adding the item.</returns>
113-
public static async Task<bool> PutItemAsync(AmazonDynamoDBClient client, Movie newMovie, string tableName)
126+
public async Task<bool> PutItemAsync(Movie newMovie, string tableName)
114127
{
115128
try
116129
{
@@ -126,7 +139,7 @@ public static async Task<bool> PutItemAsync(AmazonDynamoDBClient client, Movie n
126139
Item = item,
127140
};
128141

129-
await client.PutItemAsync(request);
142+
await _amazonDynamoDB.PutItemAsync(request);
130143
return true;
131144
}
132145
catch (ResourceNotFoundException ex)
@@ -160,8 +173,7 @@ public static async Task<bool> PutItemAsync(AmazonDynamoDBClient client, Movie n
160173
/// information that will be changed.</param>
161174
/// <param name="tableName">The name of the table that contains the movie.</param>
162175
/// <returns>A Boolean value that indicates the success of the operation.</returns>
163-
public static async Task<bool> UpdateItemAsync(
164-
AmazonDynamoDBClient client,
176+
public async Task<bool> UpdateItemAsync(
165177
Movie newMovie,
166178
MovieInfo newInfo,
167179
string tableName)
@@ -195,7 +207,7 @@ public static async Task<bool> UpdateItemAsync(
195207
TableName = tableName,
196208
};
197209

198-
await client.UpdateItemAsync(request);
210+
await _amazonDynamoDB.UpdateItemAsync(request);
199211
return true;
200212
}
201213
catch (ResourceNotFoundException ex)
@@ -228,7 +240,7 @@ public static async Task<bool> UpdateItemAsync(
228240
/// <param name="tableName">The name of the table containing the movie.</param>
229241
/// <returns>A Dictionary object containing information about the item
230242
/// retrieved.</returns>
231-
public static async Task<Dictionary<string, AttributeValue>> GetItemAsync(AmazonDynamoDBClient client, Movie newMovie, string tableName)
243+
public async Task<Dictionary<string, AttributeValue>> GetItemAsync(Movie newMovie, string tableName)
232244
{
233245
try
234246
{
@@ -244,7 +256,7 @@ public static async Task<Dictionary<string, AttributeValue>> GetItemAsync(Amazon
244256
TableName = tableName,
245257
};
246258

247-
var response = await client.GetItemAsync(request);
259+
var response = await _amazonDynamoDB.GetItemAsync(request);
248260
return response.Item;
249261
}
250262
catch (ResourceNotFoundException ex)
@@ -274,7 +286,7 @@ public static async Task<Dictionary<string, AttributeValue>> GetItemAsync(Amazon
274286
/// </summary>
275287
/// <param name="movieFileName">The full path to the JSON file.</param>
276288
/// <returns>A generic list of movie objects.</returns>
277-
public static List<Movie> ImportMovies(string movieFileName)
289+
public List<Movie> ImportMovies(string movieFileName)
278290
{
279291
var moviesList = new List<Movie>();
280292
if (!File.Exists(movieFileName))
@@ -307,8 +319,7 @@ public static List<Movie> ImportMovies(string movieFileName)
307319
/// the JSON file containing movie data.</param>
308320
/// <returns>A long integer value representing the number of movies
309321
/// imported from the JSON file.</returns>
310-
public static async Task<long> BatchWriteItemsAsync(
311-
AmazonDynamoDBClient client,
322+
public async Task<long> BatchWriteItemsAsync(
312323
string movieFileName, string tableName)
313324
{
314325
try
@@ -322,7 +333,7 @@ public static async Task<long> BatchWriteItemsAsync(
322333

323334
var context = new DynamoDBContextBuilder()
324335
// Optional call to provide a specific instance of IAmazonDynamoDB
325-
.WithDynamoDBClient(() => client)
336+
.WithDynamoDBClient(() => _amazonDynamoDB)
326337
.Build();
327338

328339
var movieBatch = context.CreateBatchWrite<Movie>(
@@ -368,8 +379,7 @@ public static async Task<long> BatchWriteItemsAsync(
368379
/// year of the movie to delete.</param>
369380
/// <returns>A Boolean value indicating the success or failure of the
370381
/// delete operation.</returns>
371-
public static async Task<bool> DeleteItemAsync(
372-
AmazonDynamoDBClient client,
382+
public async Task<bool> DeleteItemAsync(
373383
string tableName,
374384
Movie movieToDelete)
375385
{
@@ -383,7 +393,7 @@ public static async Task<bool> DeleteItemAsync(
383393

384394
var request = new DeleteItemRequest { TableName = tableName, Key = key, };
385395

386-
await client.DeleteItemAsync(request);
396+
await _amazonDynamoDB.DeleteItemAsync(request);
387397
return true;
388398
}
389399
catch (ResourceNotFoundException ex)
@@ -416,11 +426,11 @@ public static async Task<bool> DeleteItemAsync(
416426
/// <param name="year">The release year for which we want to
417427
/// view movies.</param>
418428
/// <returns>The number of movies that match the query.</returns>
419-
public static async Task<int> QueryMoviesAsync(AmazonDynamoDBClient client, string tableName, int year)
429+
public async Task<int> QueryMoviesAsync(string tableName, int year)
420430
{
421431
try
422432
{
423-
var movieTable = new TableBuilder(client, tableName)
433+
var movieTable = new TableBuilder(_amazonDynamoDB, tableName)
424434
.AddHashKey("year", DynamoDBEntryType.Numeric)
425435
.AddRangeKey("title", DynamoDBEntryType.String)
426436
.Build();
@@ -481,8 +491,7 @@ public static async Task<int> QueryMoviesAsync(AmazonDynamoDBClient client, stri
481491
// snippet-end:[DynamoDB.dotnetv4.dynamodb-basics.QueryItems]
482492

483493
// snippet-start:[DynamoDB.dotnetv4.dynamodb-basics.ScanTable]
484-
public static async Task<int> ScanTableAsync(
485-
AmazonDynamoDBClient client,
494+
public async Task<int> ScanTableAsync(
486495
string tableName,
487496
int startYear,
488497
int endYear)
@@ -512,7 +521,7 @@ public static async Task<int> ScanTableAsync(
512521
var response = new ScanResponse();
513522
do
514523
{
515-
response = await client.ScanAsync(request);
524+
response = await _amazonDynamoDB.ScanAsync(request);
516525
foundCount += response.Items.Count;
517526
response.Items.ForEach(i => DisplayItem(i));
518527
request.ExclusiveStartKey = response.LastEvaluatedKey;
@@ -540,7 +549,7 @@ public static async Task<int> ScanTableAsync(
540549
// snippet-end:[DynamoDB.dotnetv4.dynamodb-basics.ScanTable]
541550

542551
// snippet-start:[DynamoDB.dotnetv4.dynamodb-basics.DeleteTableExample]
543-
public static async Task<bool> DeleteTableAsync(AmazonDynamoDBClient client, string tableName)
552+
public async Task<bool> DeleteTableAsync(string tableName)
544553
{
545554
try
546555
{
@@ -549,7 +558,7 @@ public static async Task<bool> DeleteTableAsync(AmazonDynamoDBClient client, str
549558
TableName = tableName,
550559
};
551560

552-
var response = await client.DeleteTableAsync(request);
561+
var response = await _amazonDynamoDB.DeleteTableAsync(request);
553562

554563
Console.WriteLine($"Table {response.TableDescription.TableName} successfully deleted.");
555564
return true;
@@ -578,7 +587,7 @@ public static async Task<bool> DeleteTableAsync(AmazonDynamoDBClient client, str
578587
/// Displays a DynamoDB document on the console.
579588
/// </summary>
580589
/// <param name="document">The DynamoDB document to display.</param>
581-
public static void DisplayDocument(Document document)
590+
public void DisplayDocument(Document document)
582591
{
583592
Console.WriteLine($"{document["year"]}\t{document["title"]}");
584593
}
@@ -587,7 +596,7 @@ public static void DisplayDocument(Document document)
587596
/// Displays a DynamoDB item on the console.
588597
/// </summary>
589598
/// <param name="item">The DynamoDB item to display.</param>
590-
public static void DisplayItem(Dictionary<string, AttributeValue> item)
599+
public void DisplayItem(Dictionary<string, AttributeValue> item)
591600
{
592601
Console.WriteLine($"{item["year"].N}\t{item["title"].S}");
593602
}

dotnetv4/DynamoDB/Scenarios/DynamoDB_Basics/Basics.csproj

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
<ItemGroup>
1010
<PackageReference Include="AWSSDK.Core" Version="4.0.0.14" />
1111
<PackageReference Include="AWSSDK.DynamoDBv2" Version="4.0.2.1" />
12+
<PackageReference Include="AWSSDK.Extensions.NETCore.Setup" Version="4.0.0-preview.4" />
13+
<PackageReference Include="Microsoft.Extensions.Hosting" Version="9.0.0" />
1214
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
1315
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118">
1416
<PrivateAssets>all</PrivateAssets>

dotnetv4/DynamoDB/Scenarios/DynamoDB_Basics/DynamoDB_Basics.cs renamed to dotnetv4/DynamoDB/Scenarios/DynamoDB_Basics/DynamoDbBasics.cs

Lines changed: 30 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
using Amazon.DynamoDBv2;
55
using DynamoDBActions;
6+
using Microsoft.Extensions.DependencyInjection;
67

78
namespace Basics;
89

@@ -20,14 +21,24 @@ namespace Basics;
2021
// Scan
2122
// DeleteItemAsync
2223

23-
public class DynamoDB_Basics
24+
public class DynamoDbBasics
2425
{
2526
// Separator for the console display.
2627
private static readonly string SepBar = new string('-', 80);
28+
public static bool isInteractive = true;
2729

28-
public static async Task Main()
30+
public static async Task Main(string[] args)
2931
{
30-
var client = new AmazonDynamoDBClient();
32+
// Set up dependency injection for Amazon DynamoDB.
33+
using var host = Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args)
34+
.ConfigureServices((_, services) =>
35+
services.AddAWSService<IAmazonDynamoDB>()
36+
.AddTransient<DynamoDbWrapper>()
37+
)
38+
.Build();
39+
40+
// Now the wrapper is available for injection.
41+
var dynamoDbWrapper = host.Services.GetRequiredService<DynamoDbWrapper>();
3142

3243
var tableName = "movie_table4";
3344

@@ -38,7 +49,7 @@ public static async Task Main()
3849
// Create a new table and wait for it to be active.
3950
Console.WriteLine($"Creating the new table: {tableName}");
4051

41-
var success = await DynamoDbMethods.CreateMovieTableAsync(client, tableName);
52+
var success = await dynamoDbWrapper.CreateMovieTableAsync(tableName);
4253

4354
Console.WriteLine(success
4455
? $"\nTable: {tableName} successfully created."
@@ -53,7 +64,7 @@ public static async Task Main()
5364
Title = "Spider-Man: No Way Home",
5465
};
5566

56-
success = await DynamoDbMethods.PutItemAsync(client, newMovie, tableName);
67+
success = await dynamoDbWrapper.PutItemAsync(newMovie, tableName);
5768
if (success)
5869
{
5970
Console.WriteLine($"Added {newMovie.Title} to the table.");
@@ -75,7 +86,7 @@ public static async Task Main()
7586
Rank = 9,
7687
};
7788

78-
success = await DynamoDbMethods.UpdateItemAsync(client, newMovie, newInfo, tableName);
89+
success = await dynamoDbWrapper.UpdateItemAsync(newMovie, newInfo, tableName);
7990
if (success)
8091
{
8192
Console.WriteLine($"Successfully updated the movie: {newMovie.Title}");
@@ -89,7 +100,7 @@ public static async Task Main()
89100

90101
// Add a batch of movies to the DynamoDB table from a list of
91102
// movies in a JSON file.
92-
var itemCount = await DynamoDbMethods.BatchWriteItemsAsync(client, movieFileName, tableName);
103+
var itemCount = await dynamoDbWrapper.BatchWriteItemsAsync(movieFileName, tableName);
93104
Console.WriteLine($"Added {itemCount} movies to the table.");
94105

95106
WaitForEnter();
@@ -102,10 +113,10 @@ public static async Task Main()
102113
};
103114

104115
Console.WriteLine("Looking for the movie \"Jurassic Park\".");
105-
var item = await DynamoDbMethods.GetItemAsync(client, lookupMovie, tableName);
116+
var item = await dynamoDbWrapper.GetItemAsync(lookupMovie, tableName);
106117
if (item?.Count > 0)
107118
{
108-
DynamoDbMethods.DisplayItem(item);
119+
dynamoDbWrapper.DisplayItem(item);
109120
}
110121
else
111122
{
@@ -121,7 +132,7 @@ public static async Task Main()
121132
Year = 2010,
122133
};
123134

124-
success = await DynamoDbMethods.DeleteItemAsync(client, tableName, movieToDelete);
135+
success = await dynamoDbWrapper.DeleteItemAsync(tableName, movieToDelete);
125136

126137
if (success)
127138
{
@@ -137,21 +148,21 @@ public static async Task Main()
137148
// Use Query to find all the movies released in 2010.
138149
int findYear = 2010;
139150
Console.WriteLine($"Movies released in {findYear}");
140-
var queryCount = await DynamoDbMethods.QueryMoviesAsync(client, tableName, findYear);
151+
var queryCount = await dynamoDbWrapper.QueryMoviesAsync(tableName, findYear);
141152
Console.WriteLine($"Found {queryCount} movies released in {findYear}");
142153

143154
WaitForEnter();
144155

145156
// Use Scan to get a list of movies from 2001 to 2011.
146157
int startYear = 2001;
147158
int endYear = 2011;
148-
var scanCount = await DynamoDbMethods.ScanTableAsync(client, tableName, startYear, endYear);
159+
var scanCount = await dynamoDbWrapper.ScanTableAsync(tableName, startYear, endYear);
149160
Console.WriteLine($"Found {scanCount} movies released between {startYear} and {endYear}");
150161

151162
WaitForEnter();
152163

153164
// Delete the table.
154-
success = await DynamoDbMethods.DeleteTableAsync(client, tableName);
165+
success = await dynamoDbWrapper.DeleteTableAsync(tableName);
155166

156167
if (success)
157168
{
@@ -197,9 +208,12 @@ private static void DisplayInstructions()
197208
/// </summary>
198209
private static void WaitForEnter()
199210
{
200-
Console.WriteLine("\nPress <Enter> to continue.");
201-
Console.WriteLine(SepBar);
202-
_ = Console.ReadLine();
211+
if (isInteractive)
212+
{
213+
Console.WriteLine("\nPress <Enter> to continue.");
214+
Console.WriteLine(SepBar);
215+
_ = Console.ReadLine();
216+
}
203217
}
204218
}
205219

0 commit comments

Comments
 (0)