-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
161 lines (130 loc) · 4.85 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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.Extensions.Azure;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using MongoDB.Bson.Serialization.Serializers;
using MongoDB.Bson.Serialization;
using MongoDB.Bson;
using MongoDB.Driver;
using RESTFUL.Context;
using RESTFUL.Interfaces;
using RESTFUL.Repositories;
using RESTFUL.Services;
using RESTFUL.Settings;
using System.Text.Json;
using System;
using System.Net.Mime;
using Microsoft.AspNetCore.Http;
using System.Linq;
using Azure.Messaging.ServiceBus;
var builder = WebApplication.CreateBuilder(args);
IConfiguration configuration = builder.Configuration;
builder.Logging.AddJsonConsole();
BsonSerializer.RegisterSerializer(new GuidSerializer(BsonType.String));
BsonSerializer.RegisterSerializer(new DateTimeOffsetSerializer(BsonType.String));
var mongoDBSettings = configuration.GetSection(nameof(MongoDBSettings)).Get<MongoDBSettings>();
builder.Services.AddSingleton<IMongoClient>(serviceProvider =>
{
return new MongoClient(mongoDBSettings.ConnectionString);
});
var dbProvider = configuration.GetSection("DBProvider").Get<string>();
// we should only need one instance throughout the app lifetime
// choose which repo to use (mongo, in memory, ...)
if (dbProvider == "mongo")
{
builder.Services.AddSingleton<IItemsRepository, MongoDBItemsRepository>();
}
else if (dbProvider == "postgres")
{
var pgsqlSettings = configuration.GetSection(nameof(PGSQLSettings)).Get<PGSQLSettings>();
builder.Services.AddEntityFrameworkNpgsql()
.AddDbContext<PGSQLContext>(options =>
options.UseNpgsql(
$"Host='{pgsqlSettings.Host}'; Port={pgsqlSettings.Port};Database='{pgsqlSettings.DBName}';Username='{pgsqlSettings.User}';Password='{pgsqlSettings.Password}'"
)
);
// using scoped for services that use db contexts
builder.Services.AddScoped<IItemsRepository, PGSQLItemsRepository>();
}
else
{
var mssqlSettings = configuration.GetSection(nameof(MSSQLSettings)).Get<MSSQLSettings>();
builder.Services.AddDbContext<MSSQLContext>(options =>
options.UseSqlServer(mssqlSettings.ConnectionString ?? throw new InvalidOperationException("Connection string 'MSSQLContext' not found.")));
// using scoped for services that use db contexts
builder.Services.AddScoped<IItemsRepository, MSSQLItemsRepository>();
}
var sbSettings = configuration.GetSection(nameof(ServiceBusSettings)).Get<ServiceBusSettings>();
builder.Services.AddAzureClients(clientBuilder =>
{
clientBuilder.AddServiceBusClient(sbSettings.ConnectionString);
});
builder.Services.AddScoped<ServiceBusService>();
builder.Services.AddControllers(options =>
{
options.SuppressAsyncSuffixInActionNames = false;
});
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "RESTFUL", Version = "v1" });
});
builder.Services.AddHealthChecks()
// add healthcheck for the db and others specified here https://github.com/Xabaril/AspNetCore.Diagnostics.HealthChecks
.AddMongoDb(
mongoDBSettings.ConnectionString,
name: "mongodbhealth",
timeout: TimeSpan.FromSeconds(5),
tags: new[] { "ready" }
);
var app = builder.Build();
var env = builder.Environment;
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "RESTFUL v1"));
}
// we will use docker in production and won't need https internally
if (env.IsDevelopment())
{
app.UseHttpsRedirection();
}
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
// database can take requests
endpoints.MapHealthChecks("/health/ready", new HealthCheckOptions
{
Predicate = (check) => check.Tags.Contains("ready"),
ResponseWriter = async (context, report) =>
{
var result = JsonSerializer.Serialize(
new
{
status = report.Status.ToString(),
checks = report.Entries.Select(x => new
{
name = x.Key,
status = x.Value.Status.ToString(),
exception = x.Value.Exception != null ? x.Value.Exception.Message : "none",
duration = x.Value.Duration.ToString()
})
});
context.Response.ContentType = MediaTypeNames.Application.Json;
await context.Response.WriteAsync(result);
}
});
// service is running
endpoints.MapHealthChecks("/health/live", new HealthCheckOptions
{
Predicate = (_) => false
});
});
app.Run();