Files
weddingapi/Startup.cs
2022-02-12 20:08:48 +01:00

111 lines
3.6 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Serializers;
using MongoDB.Driver;
using weddingapi.Config;
using weddingapi.Repositories;
namespace weddingapi
{
public class Startup
{
private string MyAllowSpecificOrigins = "defaultCors";
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
BsonSerializer.RegisterSerializer(new GuidSerializer(BsonType.String));
BsonSerializer.RegisterSerializer(new DateTimeOffsetSerializer(BsonType.String));
var mongoDbConfig = Configuration.GetSection(nameof(MongoDbConfig)).Get<MongoDbConfig>();
services.AddSingleton<IMongoClient>(serviceProvider =>
{
return new MongoClient(mongoDbConfig.ConnectionString);
});
services.AddSingleton<IFamilyRepository, MongoDBFamilyRepository>();
services.AddControllers(options => {
options.SuppressAsyncSuffixInActionNames = false;
});
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "weddingapi", Version = "v1" });
});
services.AddHealthChecks()
.AddMongoDb(mongoDbConfig.ConnectionString,
name: "mongodb",
timeout: TimeSpan.FromSeconds(3),
tags: new[] { "ready" });
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "weddingapi v1"));
}
if(env.IsDevelopment())
{
app.UseHttpsRedirection();
}
app.UseRouting();
app.UseCors(MyAllowSpecificOrigins);
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHealthChecks("/health/ready", new HealthCheckOptions {
Predicate = (check) => check.Tags.Contains("ready")
});
endpoints.MapHealthChecks("/health/live", new HealthCheckOptions {
Predicate = (_) => false
});
});
}
}
}