-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathProgram.cs
More file actions
188 lines (157 loc) · 7.3 KB
/
Program.cs
File metadata and controls
188 lines (157 loc) · 7.3 KB
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
using System.Reflection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Sample.OutboxWebApi;
using Sample.OutboxWebApi.Application;
using Sample.OutboxWebApi.DataAccess;
using SecretStore;
using SlimMessageBus.Host;
using SlimMessageBus.Host.AzureServiceBus;
using SlimMessageBus.Host.Memory;
using SlimMessageBus.Host.Outbox;
using SlimMessageBus.Host.Outbox.PostgreSql;
using SlimMessageBus.Host.Outbox.Sql;
using SlimMessageBus.Host.Serialization.Json;
// Local file with secrets
Secrets.Load(@"..\..\secrets.txt");
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddHttpContextAccessor();
var configuration = builder.Configuration;
var dbProvider = DbProvider.PostgreSql;
// doc:fragment:ExampleStartup
builder.Services.AddSlimMessageBus(mbb =>
{
mbb.PerMessageScopeEnabled(false);
mbb
.AddChildBus("Memory", mbb =>
{
mbb.WithProviderMemory()
.AutoDeclareFrom(Assembly.GetExecutingAssembly(), consumerTypeFilter: t => t.Name.EndsWith("CommandHandler"));
//.UseTransactionScope(messageTypeFilter: t => t.Name.EndsWith("Command")) // Consumers/Handlers will be wrapped in a TransactionScope
//.UseSqlTransaction(messageTypeFilter: t => t.Name.EndsWith("Command")); // Consumers/Handlers will be wrapped in a SqlTransaction ending with Command
switch (dbProvider)
{
case DbProvider.SqlServer:
mbb.UseSqlTransaction(messageTypeFilter: t => t.Name.EndsWith("Command")); // Consumers/Handlers will be wrapped in a SqlTransaction ending with Command
break;
case DbProvider.PostgreSql:
mbb.UsePostgreSqlTransaction(messageTypeFilter: t => t.Name.EndsWith("Command")); // Consumers/Handlers will be wrapped in a SqlTransaction ending with Command
break;
}
})
.AddChildBus("AzureSB", mbb =>
{
mbb
.Handle<CreateCustomerCommand, Guid>(s =>
{
s.Topic("samples.outbox/customer-events", t =>
{
t.WithHandler<CreateCustomerCommandHandler, CreateCustomerCommand>()
.SubscriptionName("CreateCustomer");
});
})
.WithProviderServiceBus(cfg =>
{
cfg.ConnectionString = Secrets.Service.PopulateSecrets(configuration["Azure:ServiceBus"]);
cfg.TopologyProvisioning.CanProducerCreateTopic = true;
cfg.TopologyProvisioning.CanConsumerCreateQueue = true;
cfg.TopologyProvisioning.CanConsumerReplaceSubscriptionFilters = true;
})
.Produce<CustomerCreatedEvent>(x =>
{
x.DefaultTopic("samples.outbox/customer-events");
// OR if you want just this producer to sent via outbox
// x.UseOutbox();
})
// All outgoing messages from this bus will go out via an outbox
.UseOutbox(/* messageTypeFilter: t => t.Name.EndsWith("Command") */); // Additionally, can apply filter do determine messages that should go out via outbox
})
.AddServicesFromAssembly(Assembly.GetExecutingAssembly())
.AddJsonSerializer()
.AddAspNet();
switch (dbProvider)
{
case DbProvider.SqlServer:
SlimMessageBus.Host.Outbox.Sql.DbContext.MessageBusBuilderExtensions.AddOutboxUsingDbContext<CustomerContext>(mbb, opts =>
{
opts.PollBatchSize = 500;
opts.PollIdleSleep = TimeSpan.FromSeconds(10);
opts.MessageCleanup.Interval = TimeSpan.FromSeconds(10);
opts.MessageCleanup.Age = TimeSpan.FromMinutes(1);
//opts.SqlSettings.TransactionIsolationLevel = System.Data.IsolationLevel.RepeatableRead;
//opts.SqlSettings.Dialect = SqlDialect.SqlServer;
});
break;
case DbProvider.PostgreSql:
SlimMessageBus.Host.Outbox.PostgreSql.DbContext.MessageBusBuilderExtensions.AddOutboxUsingDbContext<CustomerContext>(mbb, opts =>
{
opts.PollBatchSize = 500;
opts.PollIdleSleep = TimeSpan.FromSeconds(10);
opts.MessageCleanup.Interval = TimeSpan.FromSeconds(10);
opts.MessageCleanup.Age = TimeSpan.FromMinutes(1);
//opts.SqlSettings.TransactionIsolationLevel = System.Data.IsolationLevel.RepeatableRead;
//opts.SqlSettings.Dialect = SqlDialect.SqlServer;
});
break;
}
});
// doc:fragment:ExampleStartup
/*
// Alternatively, if we were not using EF, we could use a SqlConnection
builder.Services.AddSlimMessageBusOutboxUsingSql(opts => { opts.PollBatchSize = 100; });
// Register in the container how to create SqlConnection
builder.Services.AddTransient(svp =>
var configuration = svp.GetRequiredService<IConfiguration>();
var connectionString = configuration.GetConnectionString("SqlServerConnection");
return new SqlConnection(connectionString);
});
*/
// Entity Framework setup - application specific EF DbContext
switch (dbProvider)
{
case DbProvider.SqlServer:
builder.Services.AddDbContext<CustomerContext>(
options => options.UseSqlServer(Secrets.Service.PopulateSecrets(builder.Configuration.GetConnectionString("SqlServerConnection")),
b => b.MigrationsAssembly("Sample.OutboxWebApi.SqlServer")));
break;
case DbProvider.PostgreSql:
builder.Services.AddDbContext<CustomerContext>(
options => options.UseNpgsql(Secrets.Service.PopulateSecrets(builder.Configuration.GetConnectionString("PostgreSqlConnection")),
b => b.MigrationsAssembly("Sample.OutboxWebApi.Postgres")));
break;
}
var app = builder.Build();
async Task CreateDbIfNotExists()
{
using var scope = app.Services.CreateScope();
var services = scope.ServiceProvider;
try
{
var context = services.GetRequiredService<CustomerContext>();
// Note: if the db is not being created, ensure that __EFMigrationsHistory does not exist
await context.Database.EnsureCreatedAsync();
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred creating the DB.");
}
// warm up the bus and force the singleton creation
_ = services.GetRequiredService<IMessageBus>();
}
await CreateDbIfNotExists();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.MapPost("/customer", ([FromBody] CreateCustomerCommand request, IMessageBus bus) => bus.Send(request))
.WithName("CreateCustomer")
.WithOpenApi();
await app.RunAsync();