Skip to content

Commit 48232ec

Browse files
author
Caleb Lloyd
committed
fix readme example
Signed-off-by: Caleb Lloyd <caleb@boxbuild.io>
1 parent 4a4e7ed commit 48232ec

File tree

9 files changed

+145
-88
lines changed

9 files changed

+145
-88
lines changed

README.md

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ The `CodeCargo.Nats.HybridCacheExtensions` package provides an extension method
2828

2929
```bash
3030
dotnet add package CodeCargo.Nats.HybridCacheExtensions
31-
dotnet add package NATS.Net
31+
dotnet add package NATS.Extensions.Microsoft.DependencyInjection
3232
```
3333

3434
### Example
@@ -38,30 +38,36 @@ using CodeCargo.Nats.HybridCacheExtensions;
3838
using Microsoft.Extensions.DependencyInjection;
3939
using Microsoft.Extensions.Hosting;
4040
using NATS.Client.Core;
41-
using NATS.Client.Hosting;
4241
using NATS.Client.KeyValueStore;
42+
using NATS.Extensions.Microsoft.DependencyInjection;
4343
using NATS.Net;
4444

45+
// Set the NATS URL, this normally comes from configuration
4546
const string natsUrl = "nats://localhost:4222";
47+
48+
// Create a host builder for a Console application
49+
// For a Web Application you can use WebApplication.CreateBuilder(args)
4650
var builder = Host.CreateDefaultBuilder(args);
4751
builder.ConfigureServices(services =>
4852
{
49-
services.AddNats(configureOpts: options => options with { Url = natsUrl });
50-
53+
services.AddNatsClient(natsBuilder => natsBuilder.ConfigureOptions(opts => opts with { Url = natsUrl }));
5154
services.AddNatsHybridCache(options =>
5255
{
5356
options.BucketName = "cache";
5457
});
5558
});
5659

5760
var host = builder.Build();
61+
62+
// Ensure that the KV Store is created
5863
var natsConnection = host.Services.GetRequiredService<INatsConnection>();
5964
var kvContext = natsConnection.CreateKeyValueStoreContext();
6065
await kvContext.CreateOrUpdateStoreAsync(new NatsKVConfig("cache")
6166
{
6267
LimitMarkerTTL = TimeSpan.FromSeconds(1)
6368
});
6469

70+
// Start the host
6571
await host.RunAsync();
6672
```
6773

@@ -71,7 +77,7 @@ await host.RunAsync();
7177

7278
```bash
7379
dotnet add package CodeCargo.Nats.DistributedCache
74-
dotnet add package NATS.Net
80+
dotnet add package NATS.Extensions.Microsoft.DependencyInjection
7581
```
7682

7783
### Example
@@ -81,30 +87,33 @@ using CodeCargo.Nats.DistributedCache;
8187
using Microsoft.Extensions.DependencyInjection;
8288
using Microsoft.Extensions.Hosting;
8389
using NATS.Client.Core;
84-
using NATS.Client.Hosting;
8590
using NATS.Client.KeyValueStore;
91+
using NATS.Extensions.Microsoft.DependencyInjection;
8692
using NATS.Net;
8793

94+
// Set the NATS URL, this normally comes from configuration
8895
const string natsUrl = "nats://localhost:4222";
96+
97+
// Create a host builder for a Console application
98+
// For a Web Application you can use WebApplication.CreateBuilder(args)
8999
var builder = Host.CreateDefaultBuilder(args);
90100
builder.ConfigureServices(services =>
91101
{
92-
services.AddNats(configureOpts: options => options with { Url = natsUrl });
93-
102+
services.AddNatsClient(natsBuilder => natsBuilder.ConfigureOptions(opts => opts with { Url = natsUrl }));
94103
services.AddNatsDistributedCache(options =>
95104
{
96105
options.BucketName = "cache";
97106
});
98107
});
99108

100109
var host = builder.Build();
110+
111+
// Ensure that the KV Store is created
101112
var natsConnection = host.Services.GetRequiredService<INatsConnection>();
102113
var kvContext = natsConnection.CreateKeyValueStoreContext();
103-
await kvContext.CreateOrUpdateStoreAsync(new NatsKVConfig("cache")
104-
{
105-
LimitMarkerTTL = TimeSpan.FromSeconds(1)
106-
});
114+
await kvContext.CreateOrUpdateStoreAsync(new NatsKVConfig("cache") { LimitMarkerTTL = TimeSpan.FromSeconds(1) });
107115

116+
// Start the host
108117
await host.RunAsync();
109118
```
110119

util/ReadmeExample/Abbreviated.cs renamed to util/ReadmeExample/DistributedCache.Example.cs

Lines changed: 5 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,12 @@
22
using Microsoft.Extensions.DependencyInjection;
33
using Microsoft.Extensions.Hosting;
44
using NATS.Client.Core;
5-
using NATS.Client.Hosting;
65
using NATS.Client.KeyValueStore;
6+
using NATS.Extensions.Microsoft.DependencyInjection;
77
using NATS.Net;
88

9-
// The abbreviated example put into the README.md
10-
// Based on Program.cs
11-
public static class Abbreviated
9+
// Example used in the README.md "Use `IDistributedCache` Directly" section
10+
public static class DistributedCacheExample
1211
{
1312
public static async Task Run(string[] args)
1413
{
@@ -18,39 +17,21 @@ public static async Task Run(string[] args)
1817
// Create a host builder for a Console application
1918
// For a Web Application you can use WebApplication.CreateBuilder(args)
2019
var builder = Host.CreateDefaultBuilder(args);
21-
22-
// Add services to the container
2320
builder.ConfigureServices(services =>
2421
{
25-
// Add NATS client
26-
services.AddNats(configureOpts: options => options with { Url = natsUrl });
27-
28-
// Add a NATS distributed cache
22+
services.AddNatsClient(natsBuilder => natsBuilder.ConfigureOptions(opts => opts with { Url = natsUrl }));
2923
services.AddNatsDistributedCache(options =>
3024
{
3125
options.BucketName = "cache";
3226
});
33-
34-
// (Optional) Add HybridCache
35-
var hybridCacheServices = services.AddHybridCache();
36-
37-
// (Optional) Use NATS Serializer for HybridCache
38-
hybridCacheServices.AddSerializerFactory(
39-
NatsOpts.Default.SerializerRegistry.ToHybridCacheSerializerFactory());
40-
41-
// Add other services as needed
4227
});
4328

44-
// Build the host
4529
var host = builder.Build();
4630

4731
// Ensure that the KV Store is created
4832
var natsConnection = host.Services.GetRequiredService<INatsConnection>();
4933
var kvContext = natsConnection.CreateKeyValueStoreContext();
50-
await kvContext.CreateOrUpdateStoreAsync(new NatsKVConfig("cache")
51-
{
52-
LimitMarkerTTL = TimeSpan.FromSeconds(1)
53-
});
34+
await kvContext.CreateOrUpdateStoreAsync(new NatsKVConfig("cache") { LimitMarkerTTL = TimeSpan.FromSeconds(1) });
5435

5536
// Start the host
5637
await host.RunAsync();

util/ReadmeExample/DistributedCache.cs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@
66
using Microsoft.Extensions.Hosting;
77
using Microsoft.Extensions.Logging;
88
using NATS.Client.Core;
9-
using NATS.Client.Hosting;
109
using NATS.Client.KeyValueStore;
10+
using NATS.Extensions.Microsoft.DependencyInjection;
1111
using NATS.Net;
1212

1313
namespace CodeCargo.ReadmeExample;
@@ -36,10 +36,12 @@ public static async Task RunAsync(string[] args)
3636
throw new InvalidOperationException("Cannot find connection string for NATS");
3737
}
3838

39+
// Create a host builder for a Console application
40+
// For a Web Application you can use WebApplication.CreateBuilder(args)
3941
var builder = Host.CreateDefaultBuilder(args);
4042
builder.ConfigureServices(services =>
4143
{
42-
services.AddNats(configureOpts: options => options with { Url = natsConnectionString });
44+
services.AddNatsClient(natsBuilder => natsBuilder.ConfigureOptions(opts => opts with { Url = natsConnectionString }));
4345
services.AddNatsDistributedCache(options =>
4446
{
4547
options.BucketName = "cache";
@@ -51,13 +53,15 @@ public static async Task RunAsync(string[] args)
5153
var host = builder.Build();
5254
var lifetime = host.Services.GetRequiredService<IHostApplicationLifetime>();
5355

56+
// Ensure that the KV Store is created
5457
Console.WriteLine("Creating KV store...");
5558
var natsConnection = host.Services.GetRequiredService<INatsConnection>();
5659
var kvContext = natsConnection.CreateKeyValueStoreContext();
5760
await kvContext.CreateOrUpdateStoreAsync(
5861
new NatsKVConfig("cache") { LimitMarkerTTL = TimeSpan.FromSeconds(1) }, startupCts.Token);
5962
Console.WriteLine("KV store created");
6063

64+
// Start the host
6165
Console.WriteLine("Starting app...");
6266
using var appCts = new CancellationTokenSource();
6367
var appTask = Task.Run(async () =>
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
using CodeCargo.Nats.HybridCacheExtensions;
2+
using Microsoft.Extensions.DependencyInjection;
3+
using Microsoft.Extensions.Hosting;
4+
using NATS.Client.Core;
5+
using NATS.Client.KeyValueStore;
6+
using NATS.Extensions.Microsoft.DependencyInjection;
7+
using NATS.Net;
8+
9+
// Example used in the README.md "Use with `HybridCache`" section
10+
public static class HybridCacheExample
11+
{
12+
public static async Task Run(string[] args)
13+
{
14+
// Set the NATS URL, this normally comes from configuration
15+
const string natsUrl = "nats://localhost:4222";
16+
17+
// Create a host builder for a Console application
18+
// For a Web Application you can use WebApplication.CreateBuilder(args)
19+
var builder = Host.CreateDefaultBuilder(args);
20+
builder.ConfigureServices(services =>
21+
{
22+
services.AddNatsClient(natsBuilder => natsBuilder.ConfigureOptions(opts => opts with { Url = natsUrl }));
23+
services.AddNatsHybridCache(options =>
24+
{
25+
options.BucketName = "cache";
26+
});
27+
});
28+
29+
var host = builder.Build();
30+
31+
// Ensure that the KV Store is created
32+
var natsConnection = host.Services.GetRequiredService<INatsConnection>();
33+
var kvContext = natsConnection.CreateKeyValueStoreContext();
34+
await kvContext.CreateOrUpdateStoreAsync(new NatsKVConfig("cache") { LimitMarkerTTL = TimeSpan.FromSeconds(1) });
35+
36+
// Start the host
37+
await host.RunAsync();
38+
}
39+
}

util/ReadmeExample/HybridCache.cs

Lines changed: 16 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@
66
using Microsoft.Extensions.Hosting;
77
using Microsoft.Extensions.Logging;
88
using NATS.Client.Core;
9-
using NATS.Client.Hosting;
109
using NATS.Client.KeyValueStore;
10+
using NATS.Extensions.Microsoft.DependencyInjection;
1111
using NATS.Net;
1212

1313
namespace CodeCargo.ReadmeExample;
@@ -36,10 +36,12 @@ public static async Task RunAsync(string[] args)
3636
throw new InvalidOperationException("Cannot find connection string for NATS");
3737
}
3838

39+
// Create a host builder for a Console application
40+
// For a Web Application you can use WebApplication.CreateBuilder(args)
3941
var builder = Host.CreateDefaultBuilder(args);
4042
builder.ConfigureServices(services =>
4143
{
42-
services.AddNats(configureOpts: options => options with { Url = natsConnectionString });
44+
services.AddNatsClient(natsBuilder => natsBuilder.ConfigureOptions(opts => opts with { Url = natsConnectionString }));
4345
services.AddNatsHybridCache(options =>
4446
{
4547
options.BucketName = "cache";
@@ -51,13 +53,15 @@ public static async Task RunAsync(string[] args)
5153
var host = builder.Build();
5254
var lifetime = host.Services.GetRequiredService<IHostApplicationLifetime>();
5355

56+
// Ensure that the KV Store is created
5457
Console.WriteLine("Creating KV store...");
5558
var natsConnection = host.Services.GetRequiredService<INatsConnection>();
5659
var kvContext = natsConnection.CreateKeyValueStoreContext();
5760
await kvContext.CreateOrUpdateStoreAsync(
5861
new NatsKVConfig("cache") { LimitMarkerTTL = TimeSpan.FromSeconds(1) }, startupCts.Token);
5962
Console.WriteLine("KV store created");
6063

64+
// Start the host
6165
Console.WriteLine("Starting app...");
6266
using var appCts = new CancellationTokenSource();
6367
var appTask = Task.Run(async () =>
@@ -117,31 +121,24 @@ private static async Task WaitForApplicationStartAsync(IHostApplicationLifetime
117121
}
118122
}
119123

120-
public class HybridCacheService
124+
public class HybridCacheService(HybridCache cache, ILogger<HybridCacheService> logger)
121125
{
122-
private readonly HybridCache _cache;
123-
private readonly ILogger<HybridCacheService> _logger;
124-
125-
public HybridCacheService(HybridCache cache, ILogger<HybridCacheService> logger)
126-
{
127-
_cache = cache;
128-
_logger = logger;
129-
}
130-
131126
public async Task Run()
132127
{
133-
_logger.LogInformation("------------------------------------------");
134-
_logger.LogInformation("HybridCache example");
128+
logger.LogInformation("------------------------------------------");
129+
logger.LogInformation("HybridCache example");
135130

136131
const string key = "hybrid-cache-greeting";
137132

138-
var result = await _cache.GetOrCreateAsync<string>(
133+
var result = await cache.GetOrCreateAsync<Person>(
139134
key,
140-
_ => ValueTask.FromResult("Hello from NATS Hybrid Cache!"),
135+
_ => ValueTask.FromResult(new Person("John Doe", 30)),
141136
new HybridCacheEntryOptions { Expiration = TimeSpan.FromMinutes(1) });
142-
_logger.LogInformation("Got/created value from cache: {Result}", result);
137+
logger.LogInformation("Got/created value from cache: {Result}", result);
143138

144-
await _cache.RemoveAsync(key);
145-
_logger.LogInformation("Removed value from cache");
139+
await cache.RemoveAsync(key);
140+
logger.LogInformation("Removed value from cache");
146141
}
142+
143+
private record Person(string Name, int Age);
147144
}

util/ReadmeExample/ReadmeExample.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
<ItemGroup>
1010
<PackageReference Include="Aspire.Hosting.Testing" Version="9.2.1" />
11-
<PackageReference Include="NATS.Net" Version="2.6.0" />
11+
<PackageReference Include="NATS.Extensions.Microsoft.DependencyInjection" Version="2.6.0" />
1212
</ItemGroup>
1313

1414
<ItemGroup>

util/ReadmeExample/packages.linux-x64.lock.json

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -36,20 +36,14 @@
3636
"System.IO.Hashing": "9.0.3"
3737
}
3838
},
39-
"NATS.Net": {
39+
"NATS.Extensions.Microsoft.DependencyInjection": {
4040
"type": "Direct",
4141
"requested": "[2.6.0, )",
4242
"resolved": "2.6.0",
43-
"contentHash": "rE1jwq7HMLMfOscaC5dOh1VSOrkA4a2EeKnehaFuiygo3VC2g9ONae5KsNSEdioOoHlRq6xDG9Wu4qNa+1tuCQ==",
43+
"contentHash": "riwSWcfutHlt3gQQU3wgImjgNNLnS6y/5G5Rj7XEGNnoNCEJvtdVHQyaICHg05ehexLiDf4idJrR/KVTldWD2w==",
4444
"dependencies": {
45-
"NATS.Client.Core": "2.6.0",
46-
"NATS.Client.Hosting": "2.6.0",
47-
"NATS.Client.JetStream": "2.6.0",
48-
"NATS.Client.KeyValueStore": "2.6.0",
49-
"NATS.Client.ObjectStore": "2.6.0",
50-
"NATS.Client.Serializers.Json": "2.6.0",
51-
"NATS.Client.Services": "2.6.0",
52-
"NATS.Client.Simplified": "2.6.0"
45+
"Microsoft.Extensions.Hosting.Abstractions": "8.0.0",
46+
"NATS.Net": "2.6.0"
5347
}
5448
},
5549
"StyleCop.Analyzers": {
@@ -837,6 +831,21 @@
837831
"NATS.Client.Serializers.Json": "2.6.0"
838832
}
839833
},
834+
"NATS.Net": {
835+
"type": "Transitive",
836+
"resolved": "2.6.0",
837+
"contentHash": "rE1jwq7HMLMfOscaC5dOh1VSOrkA4a2EeKnehaFuiygo3VC2g9ONae5KsNSEdioOoHlRq6xDG9Wu4qNa+1tuCQ==",
838+
"dependencies": {
839+
"NATS.Client.Core": "2.6.0",
840+
"NATS.Client.Hosting": "2.6.0",
841+
"NATS.Client.JetStream": "2.6.0",
842+
"NATS.Client.KeyValueStore": "2.6.0",
843+
"NATS.Client.ObjectStore": "2.6.0",
844+
"NATS.Client.Serializers.Json": "2.6.0",
845+
"NATS.Client.Services": "2.6.0",
846+
"NATS.Client.Simplified": "2.6.0"
847+
}
848+
},
840849
"Nerdbank.Streams": {
841850
"type": "Transitive",
842851
"resolved": "2.11.90",

0 commit comments

Comments
 (0)