Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
141 lines (120 loc) · 7.72 KB
/
Copy pathProgram.cs
File metadata and controls
141 lines (120 loc) · 7.72 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
using Contoso.Shopping.Application;
using Contoso.Shopping.Infrastructure.Clients.Customers;
using Contoso.Shopping.Infrastructure.Clients.Products;
using Contoso.Shopping.Infrastructure.Clients.SendGrid;
using Contoso.Shopping.Infrastructure.Repositories;
using Contoso.Shopping.Subscribe.Subscribers;
using CoreEx.Azure.Messaging.ServiceBus;
using Microsoft.Extensions.Options;
using OpenTelemetry;
using OpenTelemetry.Trace;
using StackExchange.Redis;
using System.Net.Http.Headers;
using ZiggyCreatures.Caching.Fusion;
using ZiggyCreatures.Caching.Fusion.Backplane.StackExchangeRedis;
namespace Contoso.Shopping.Subscribe;
public class Program
{
private static void Main(string[] args)
{
// Create the web builder.
var builder = WebApplication.CreateBuilder(args);
// Add CoreEx host settings.
builder.AddHostSettings();
builder.Services.Configure<OpenTelemetry.Logs.OpenTelemetryLoggerOptions>(o => o.IncludeScopes = true);
// Add CoreEx services.
builder.Services
.AddPrecisionTimeProvider()
.AddExecutionContext()
.AddReferenceDataOrchestrator()
.AddMvcWebApi()
.AddHttpWebApi()
.AddHostedServiceManager();
// Add all the dynamically registered services.
builder.Services.AddDynamicServicesUsing<ProductModifySubscriber, ReferenceDataProvider, ReferenceDataRepository>();
// Add L1/L2 caching services.
builder.Services.AddMemoryCache(); // Adds the in-memory cache - L1.
builder.AddRedisDistributedCache("redis"); // Adds Redis as the distributed cache (using Aspire library) - L2.
// Add and wire-up FusionCache including backplane.
builder.Services.AddFusionCache()
.WithRegisteredMemoryCache()
.WithRegisteredDistributedCache()
.WithBackplane(sp => new RedisBackplane(new RedisBackplaneOptions { Configuration = sp.GetRequiredService<IOptions<ConfigurationOptions>>().Value.ToString() }))
.WithSystemTextJsonSerializer(JsonDefaults.SerializerOptions);
// Add CoreEx caching services.
builder.Services
.AddFusionHybridCache() // Adds the CoreEx.Caching.IHybridCache for FusionCache.
.AddDefaultCacheKeyProvider() // Adds the default CoreEx.Caching.ICacheKeyProvider.
.AddRedisCoordination() // Adds Redis-backed synchronization and idempotency storage.
.AddIdempotencyProvider(); // Adds the ASP.NET Core idempotency integration.
// Add the repository and related outbox services.
builder.AddSqlServerClient("SqlServer"); // Adds the SqlServerClient (using Aspire library).
builder.Services
.AddSqlServerDatabase() // Adds the SqlServerDatabase.
.AddSqlServerUnitOfWork() // Adds the SqlServerUnitOfWork for the SqlServerDatabase.
.AddSqlServerOutboxPublisher() // Adds the SqlServerOutboxPublisher for the SqlServerUnitOfWork.
.AddDbContext<ShoppingDbContext>() // Adds the standard EF DbContext.
.AddEfDb<ShoppingEfDb>(); // Adds the CoreEx extended EF service.
// Add Azure Service Bus client using Aspire.
builder.AddAzureServiceBusClient("ServiceBus");
builder.Services.AddAzureServiceBusPublisher((_, c) => // Adds the service bus as the IEventPublisher.
{
c.SessionIdStrategy = ServiceBusSessionStrategy.UsePartitionKeyConvertedToAnId; // Use a partition-id as the session-id.
}, addAsDefaultIEventPublisher: false);
// Add event formatter and subscribed-manager.
builder.Services
.AddEventFormatter() // Adds the EventFormatter to enable message parsing.
.AddNamedDestinationProvider() // Adds the NamedDestinationProvider; events to the shared topic, commands to per-domain queues.
.AddSubscribedManager((_, c) => c.AddSubscribersUsing<ProductModifySubscriber>()); // Adds the SubscribedManager and dynamically links to the individual Subscribers.
// Creates the Azure Service Bus receiving services builder.
builder.Services.AzureServiceBusReceiving()
.WithSessionReceiver(_ =>
{ // Adds the service bus receiver to pump messages to the subscriber.
var o = ServiceBusSessionReceiverOptions.CreateForTopicSubscription(); // Set the topic and subscription from configuration.
o.SessionProcessorOptions.MaxConcurrentSessions = 4; // Set the maximum number of concurrent sessions to process.
return o;
})
.WithSubscribedSubscriber() // Adds the service bus subscriber using the ^ SubscribedManager.
.WithHostedService() // Adds the ^ service bus receiver as a hosted service.
.Build(); // Builds all the ^ services and adds to the service collection.
// Add external API services.
builder.AddTypedHttpClient<ProductsHttpClient>("ProductsApi");
builder.AddTypedHttpClient<CustomersHttpClient>("CustomersApi");
builder.AddTypedHttpClient<SendGridHttpClient>("SendGrid", client => client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", builder.Configuration["SendGrid:ApiKey"]));
builder.Services.Configure<SendGridOptions>(builder.Configuration.GetSection("SendGrid"));
// Post-configure all health-checks; adds the standard tags.
builder.Services.PostConfigureAllHealthChecks();
// Add the ASP.NET Core services.
builder.Services.AddControllers();
// Add the OpenAPI services.
builder.Services.AddOpenApiDocument(s =>
{
s.Title = builder.Environment.ApplicationName;
s.AddCoreExConfiguration();
});
// Add OpenTelemetry tracing.
#if NET8_0
// Workaround: net8.0's regex automata cap is too low for the combined ActivitySource patterns below; remove once net8.0 support is dropped.
AppContext.SetData("REGEX_NONBACKTRACKING_MAX_AUTOMATA_SIZE", 10_000);
#endif
builder.WithCoreExTelemetry()
.WithCoreExServiceBusTelemetry()
.WithCoreExSqlServerTelemetry()
.UseOtlpExporter();
// Build the application.
var app = builder.Build();
// Configure the pipeline/middleware (order is important).
app.UseCoreExExceptionHandler();
app.UseExecutionContext();
app.UseHttpsRedirection();
// app.UseAuthentication(); // TODO: register an authentication scheme (builder.Services.AddAuthentication(...)) then uncomment.
app.UseAuthorization();
app.MapControllers();
app.UseOpenApi();
app.UseSwaggerUi();
app.MapHealthChecks(); // Secure by default: detailed endpoints are disabled unless explicitly enabled (HealthCheckOptions.AreDetailedEndpointsEnabled) and secured (detailedGroupConfigure, e.g. g => g.RequireAuthorization()); basic live/startup/ready checks stay anonymous for orchestrator probes.
app.MapHostedServices(/* groupConfigure: g => g.RequireAuthorization() */); // Pause/resume management endpoints are admin-only and must be secured.
// Run the application.
app.Run();
}
}