59 lines
2.2 KiB
C#
59 lines
2.2 KiB
C#
using Hutopy.Application.Common.Interfaces;
|
|
using Hutopy.Domain.Constants;
|
|
using Hutopy.Infrastructure.Data;
|
|
using Hutopy.Infrastructure.Data.Interceptors;
|
|
using Hutopy.Infrastructure.Identity;
|
|
using Microsoft.AspNetCore.Identity;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.EntityFrameworkCore.Diagnostics;
|
|
using Microsoft.Extensions.Configuration;
|
|
|
|
namespace Microsoft.Extensions.DependencyInjection;
|
|
|
|
public static class DependencyInjection
|
|
{
|
|
public static IServiceCollection AddInfrastructureServices(this IServiceCollection services, IConfiguration configuration)
|
|
{
|
|
// Replace password in the connection string with env var.
|
|
var connectionString = configuration.GetConnectionString("DefaultConnection") ?? "";
|
|
var dbPassword = Environment.GetEnvironmentVariable("DB_PASSWORD");
|
|
|
|
connectionString = connectionString.Replace("{DB_PASSWORD}", dbPassword);
|
|
|
|
Guard.Against.Null(connectionString, message: "Connection string 'DefaultConnection' not found.");
|
|
|
|
services.AddScoped<ISaveChangesInterceptor, AuditableEntityInterceptor>();
|
|
services.AddScoped<ISaveChangesInterceptor, DispatchDomainEventsInterceptor>();
|
|
|
|
services.AddDbContext<ApplicationDbContext>((sp, options) =>
|
|
{
|
|
options.AddInterceptors(sp.GetServices<ISaveChangesInterceptor>());
|
|
|
|
options.UseSqlServer(connectionString);
|
|
});
|
|
|
|
services.AddScoped<IApplicationDbContext>(provider => provider.GetRequiredService<ApplicationDbContext>());
|
|
|
|
services.AddScoped<ApplicationDbContextInitialiser>();
|
|
|
|
services.AddAuthentication()
|
|
.AddBearerToken(IdentityConstants.BearerScheme);
|
|
|
|
services.AddAuthorizationBuilder();
|
|
|
|
services
|
|
.AddIdentityCore<ApplicationUser>()
|
|
.AddRoles<IdentityRole>()
|
|
.AddEntityFrameworkStores<ApplicationDbContext>()
|
|
.AddApiEndpoints();
|
|
|
|
services.AddSingleton(TimeProvider.System);
|
|
services.AddTransient<IIdentityService, IdentityService>();
|
|
|
|
services.AddAuthorization(options =>
|
|
options.AddPolicy(Policies.CanPurge, policy => policy.RequireRole(Roles.Administrator)));
|
|
|
|
return services;
|
|
}
|
|
}
|