Files
vegasco/src/WebApi/Common/DependencyInjectionExtensions.cs

139 lines
3.7 KiB
C#
Raw Normal View History

using Asp.Versioning;
using FluentValidation;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Options;
using Vegasco.WebApi.Authentication;
using Vegasco.WebApi.Endpoints;
using Vegasco.WebApi.Endpoints.OpenApi;
2024-08-17 16:38:40 +02:00
using Vegasco.WebApi.Persistence;
namespace Vegasco.WebApi.Common;
public static class DependencyInjectionExtensions
{
/// <summary>
/// Adds all the WebApi related services to the Dependency Injection container.
/// </summary>
/// <param name="services"></param>
/// <param name="configuration"></param>
/// <param name="environment"></param>
public static void AddWebApiServices(this IHostApplicationBuilder builder)
{
builder.Services
.AddMiscellaneousServices()
.AddOpenApi()
.AddApiVersioning()
.AddAuthenticationAndAuthorization(builder.Environment);
builder.AddDbContext();
}
private static IServiceCollection AddMiscellaneousServices(this IServiceCollection services)
{
services.AddResponseCompression();
services.AddValidatorsFromAssemblies(
[
typeof(IWebApiMarker).Assembly
], ServiceLifetime.Singleton);
services.AddHealthChecks();
services.AddEndpointsFromAssemblyContaining<IWebApiMarker>();
2024-08-17 16:38:40 +02:00
services.AddHttpContextAccessor();
2024-08-24 13:43:43 +02:00
services.AddHostedService<ApplyMigrationsService>();
return services;
}
private static IServiceCollection AddOpenApi(this IServiceCollection services)
{
services.ConfigureOptions<ConfigureSwaggerGenOptions>();
services.AddEndpointsApiExplorer();
2024-08-17 16:38:40 +02:00
services.AddSwaggerGen(o =>
{
o.CustomSchemaIds(type =>
{
if (string.IsNullOrEmpty(type.FullName))
{
return type.Name;
}
var fullClassName = type.FullName;
if (!string.IsNullOrEmpty(type.Namespace))
{
fullClassName = fullClassName
.Replace(type.Namespace, "")
.TrimStart('.');
}
fullClassName = fullClassName.Replace('+', '_');
2024-08-17 16:38:40 +02:00
return fullClassName;
});
});
return services;
}
private static IServiceCollection AddApiVersioning(this IServiceCollection services)
{
services.AddApiVersioning(o =>
{
o.DefaultApiVersion = new ApiVersion(1);
o.ApiVersionReader = new UrlSegmentApiVersionReader();
o.ReportApiVersions = true;
})
.AddApiExplorer(o =>
{
o.GroupNameFormat = "'v'V";
o.SubstituteApiVersionInUrl = true;
});
return services;
}
private static IServiceCollection AddAuthenticationAndAuthorization(this IServiceCollection services, IHostEnvironment environment)
{
services.AddOptions<JwtOptions>()
.BindConfiguration(JwtOptions.SectionName)
.ValidateFluently()
.ValidateOnStart();
var jwtOptions = services.BuildServiceProvider().GetRequiredService<IOptions<JwtOptions>>();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, o =>
{
o.MetadataAddress = jwtOptions.Value.MetadataUrl;
o.TokenValidationParameters.ValidAudience = jwtOptions.Value.ValidAudience;
o.TokenValidationParameters.ValidateAudience = true;
if (!string.IsNullOrWhiteSpace(jwtOptions.Value.NameClaimType))
{
o.TokenValidationParameters.NameClaimType = jwtOptions.Value.NameClaimType;
}
o.RequireHttpsMetadata = !jwtOptions.Value.AllowHttpMetadataUrl && !environment.IsDevelopment();
});
services.AddAuthorizationBuilder()
.AddPolicy(Constants.Authorization.RequireAuthenticatedUserPolicy, p => p
.RequireAuthenticatedUser()
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme));
2024-08-17 16:38:40 +02:00
services.AddScoped<UserAccessor>();
return services;
}
private static IHostApplicationBuilder AddDbContext(this IHostApplicationBuilder builder)
2024-08-17 16:38:40 +02:00
{
builder.AddNpgsqlDbContext<ApplicationDbContext>(Server.AppHost.Shared.Constants.Database.Name);
return builder;
}
}