-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
99 lines (78 loc) · 3.01 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
using System.Text.Json.Serialization;
using Rebus.Bus;
using Rebus.Config;
using Rebus.Handlers;
using Rebus.Retry.Simple;
using Rebus.Routing.TypeBased;
using Rebus.Serialization.Json;
using Rebus.Transport.InMem;
var builder = WebApplication.CreateSlimBuilder(args);
builder.Services.AddRebus(configure =>
{
configure.Options(o => o.RetryStrategy());
// 👇 Use System.Text.Json with source generators no reflection based serialization!
configure.Serialization(c => c.UseSystemTextJson( AppJsonSerializerContext.Default.Options));
configure.Routing(r => r.TypeBased().Map<SimpleCommand>("my-queue"));
// 👇 Use InMemoryTransport for testing
configure.Transport(t => t.UseInMemoryTransport(new InMemNetwork(),"my-queue"));
return configure;
});
builder.Services.AddRebusHandler<MyHandler>();
builder.Services.ConfigureHttpJsonOptions(options =>
{
options.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonSerializerContext.Default);
});
var app = builder.Build();
var sampleTodos = new Todo[]
{
new(1, "Walk the dog"),
new(2, "Do the dishes", DateOnly.FromDateTime(DateTime.Now)),
new(3, "Do the laundry", DateOnly.FromDateTime(DateTime.Now.AddDays(1))),
new(4, "Clean the bathroom"),
new(5, "Clean the car", DateOnly.FromDateTime(DateTime.Now.AddDays(2)))
};
var todosApi = app.MapGroup("/todos");
todosApi.MapGet("/", () => sampleTodos);
todosApi.MapGet("/{id}", (int id) =>
sampleTodos.FirstOrDefault(a => a.Id == id) is { } todo
? Results.Ok(todo)
: Results.NotFound());
var cancellationToken = app.Services.GetRequiredService<IHostApplicationLifetime>().ApplicationStopping;
var bus = app.Services.GetRequiredService<IBus>();
// 👇 generate some messages
_ = Sender(cancellationToken, bus, app.Services.GetRequiredService<ILogger<Program>>());
app.Run();
static async Task Sender(CancellationToken cancellationToken, IBus bus, ILogger<Program> logger)
{
var timer = new PeriodicTimer(TimeSpan.FromSeconds(1));
while (await timer.WaitForNextTickAsync(cancellationToken))
{
try
{
await bus.SendLocal(new SimpleCommand(Guid.NewGuid().ToString(), DateTime.Now));
}
catch (Exception e)
{
logger.LogError(e, "Failed to send command");
}
}
}
public record SimpleCommand(string Id, DateTime CreatedAt);
public class MyHandler : IHandleMessages<SimpleCommand>
{
private readonly ILogger<MyHandler> _logger;
public MyHandler(ILogger<MyHandler> logger)
{
_logger = logger;
}
public Task Handle(SimpleCommand message)
{
_logger.LogInformation("Received command with ID {Id} created at {CreatedAt}", message.Id, message.CreatedAt);
return Task.CompletedTask;
}
}
public record Todo(int Id, string? Title, DateOnly? DueBy = null, bool IsComplete = false);
[JsonSerializable(typeof(Todo[]))]
// 👇 add type to serializer
[JsonSerializable(typeof(SimpleCommand))]
internal partial class AppJsonSerializerContext : JsonSerializerContext;