-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathProgram.cs
146 lines (127 loc) · 5.92 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
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
using EventSourcing.Common.Command;
using EventSourcing.Common.EventStore;
using EventSourcing.Common.Projection;
using EventSourcing.Common.Query;
using EventSourcing.Common.Reaction;
using EventSourcing.Common.SerializedEvent;
using EventSourcing.Common.Util;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.Extensions.Logging.Console;
var builder = WebApplication.CreateBuilder(args);
var postgresConnectionString =
$"Host={GetEnvVar("EVENT_STORE_HOST")};" +
$"Port={GetEnvVar("EVENT_STORE_PORT")};" +
$"Database={GetEnvVar("EVENT_STORE_DATABASE_NAME")};" +
$"Username={GetEnvVar("EVENT_STORE_USER")};" +
$"Password={GetEnvVar("EVENT_STORE_PASSWORD")};";
var postgresTableName = GetEnvVar("EVENT_STORE_CREATE_TABLE_WITH_NAME");
builder.Services.AddSingleton(_ => new PostgresConnectionPool(postgresConnectionString));
builder.Services.AddSingleton(_ => new Deserializer());
builder.Services.AddSingleton(_ => new Serializer());
builder.Services.AddScoped<PostgresTransactionalEventStore>(provider => {
var pool = provider.GetRequiredService<PostgresConnectionPool>();
var deserializer = provider.GetRequiredService<Deserializer>();
var serializer = provider.GetRequiredService<Serializer>();
var eventStoreTable = postgresTableName;
var logger = provider.GetRequiredService<ILogger<PostgresTransactionalEventStore>>();
return new PostgresTransactionalEventStore(pool, serializer, deserializer, eventStoreTable, logger);
});
builder.Services.AddSingleton<PostgresInitializer>(provider => {
var pool = provider.GetRequiredService<PostgresConnectionPool>();
var logger = provider.GetRequiredService<ILogger<PostgresInitializer>>();
return new PostgresInitializer(
pool,
GetEnvVar("EVENT_STORE_DATABASE_NAME"),
GetEnvVar("EVENT_STORE_CREATE_TABLE_WITH_NAME"),
GetEnvVar("EVENT_STORE_CREATE_REPLICATION_USER_WITH_USERNAME"),
GetEnvVar("EVENT_STORE_CREATE_REPLICATION_USER_WITH_PASSWORD"),
GetEnvVar("EVENT_STORE_CREATE_REPLICATION_PUBLICATION"),
logger
);
});
var mongoConnectionString =
$"mongodb://{GetEnvVar("MONGODB_PROJECTION_DATABASE_USERNAME")}:{GetEnvVar("MONGODB_PROJECTION_DATABASE_PASSWORD")}@" +
$"{GetEnvVar("MONGODB_PROJECTION_HOST")}:{GetEnvVar("MONGODB_PROJECTION_PORT")}/" +
$"{GetEnvVar("MONGODB_PROJECTION_DATABASE_NAME")}" +
"?serverSelectionTimeoutMS=10000&connectTimeoutMS=10000&authSource=admin";
var mongoDatabaseName = GetEnvVar("MONGODB_PROJECTION_DATABASE_NAME");
builder.Services.AddSingleton(_ => new MongoSessionPool(mongoConnectionString));
builder.Services.AddScoped<MongoTransactionalProjectionOperator>(provider =>
{
var sessionPool = provider.GetRequiredService<MongoSessionPool>();
var logger = provider.GetRequiredService<ILogger<MongoTransactionalProjectionOperator>>();
return new MongoTransactionalProjectionOperator(sessionPool, mongoDatabaseName, logger);
});
builder.Services.AddSingleton<MongoInitializer>(provider => {
var pool = provider.GetRequiredService<MongoSessionPool>();
var logger = provider.GetRequiredService<ILogger<MongoInitializer>>();
return new MongoInitializer(
pool,
GetEnvVar("MONGODB_PROJECTION_DATABASE_NAME"),
logger
);
});
AddScopedInheritors<CommandController>(builder.Services);
AddScopedInheritors<CommandHandler>(builder.Services);
AddScopedInheritors<ProjectionController>(builder.Services);
AddScopedInheritors<ProjectionHandler>(builder.Services);
AddScopedInheritors<QueryController>(builder.Services);
AddScopedInheritors<QueryHandler>(builder.Services);
AddScopedInheritors<ReactionController>(builder.Services);
AddScopedInheritors<ReactionHandler>(builder.Services);
builder.Services.Scan(scan => scan
.FromAssemblies(AppDomain.CurrentDomain.GetAssemblies())
.AddClasses(classes => classes.Where(type =>
type.Namespace != null && type.Namespace.StartsWith("EventSourcing.Domain")))
.AsSelfWithInterfaces()
.WithScopedLifetime());
builder.Services.AddControllers();
builder.Services.AddLogging(logging =>
{
logging.ClearProviders();
logging.AddConsole(options =>
{
options.FormatterName = "MainLogger";
options.LogToStandardErrorThreshold = LogLevel.Error;
}).AddConsoleFormatter<Logger, ConsoleFormatterOptions>();
logging.SetMinimumLevel(LogLevel.Debug);
logging.AddFilter("EventSourcing", LogLevel.Debug);
logging.AddFilter("Microsoft", LogLevel.Information);
});
var app = builder.Build();
// Initialize databases
var postgresInitializer = app.Services.GetRequiredService<PostgresInitializer>();
var mongoInitializer = app.Services.GetRequiredService<MongoInitializer>();
postgresInitializer.Initialize();
mongoInitializer.Initialize();
// Register app exception handler
app.UseExceptionHandler(errorApp =>
{
errorApp.Run(async context =>
{
var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();
var exception = exceptionHandlerPathFeature?.Error;
var logger = context.RequestServices.GetRequiredService<ILogger<Program>>();
logger.LogError(exception, "Unhandled exception: {Message}. Stack Trace: {StackTrace}", exception?.Message, exception?.StackTrace);
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new {
error = exception?.Message,
stackTrace = exception?.StackTrace
});
});
});
// Run app
app.MapControllers();
app.Run();
return;
static string GetEnvVar(string name) =>
Environment.GetEnvironmentVariable(name) ?? throw new ArgumentNullException(name);
static void AddScopedInheritors<T>(IServiceCollection services) {
services.Scan(scan => scan
.FromAssemblyOf<T>()
.AddClasses(classes => classes
.AssignableTo<T>())
.AsSelfWithInterfaces()
.WithScopedLifetime());
}