74 lines
2.9 KiB
C#
74 lines
2.9 KiB
C#
using System;
|
|
using Hutopy.Application.Common.Interfaces;
|
|
using Hutopy.Domain.Constants;
|
|
using Hutopy.Domain.Interfaces;
|
|
using Hutopy.Infrastructure.Data;
|
|
using Hutopy.Infrastructure.Data.Interceptors;
|
|
using Hutopy.Infrastructure.Identity;
|
|
using Hutopy.Infrastructure.Services;
|
|
using Hutopy.Infrastructure.Stripe;
|
|
using Microsoft.AspNetCore.Identity;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.EntityFrameworkCore.Diagnostics;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
namespace Hutopy.Infrastructure;
|
|
|
|
public static class DependencyInjection
|
|
{
|
|
public static IServiceCollection AddInfrastructureServices(this IServiceCollection services, IConfiguration configuration)
|
|
{
|
|
// Replace password in the connection string with env var in local environment.
|
|
// Prod will use the connectionString stored in the vault with password in it directly.
|
|
var connectionString = configuration.GetConnectionString("DefaultConnection") ?? "";
|
|
|
|
var dbPassword = configuration["DB_PASSWORD"] ?? "";
|
|
var dbHost = configuration["DB_HOST"] ?? "localhost";
|
|
|
|
if (dbHost == "localhost" && dbPassword != string.Empty)
|
|
{
|
|
connectionString = connectionString.Replace("{DB_PASSWORD}", dbPassword);
|
|
connectionString = connectionString.Replace("{DB_HOST}", dbHost);
|
|
}
|
|
|
|
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<ApplicationDbContextInitializer>();
|
|
|
|
services.AddAuthentication()
|
|
.AddBearerToken(IdentityConstants.BearerScheme);
|
|
|
|
services.AddAuthorizationBuilder();
|
|
services.AddScoped<IUserService, UserService>();
|
|
|
|
|
|
// Might need to change and use AddIdentity<User, Role>() when we need to integrate connection via third party ( facebook, google )
|
|
services
|
|
.AddIdentityCore<ApplicationUser>()
|
|
.AddRoles<IdentityRole>()
|
|
.AddEntityFrameworkStores<ApplicationDbContext>()
|
|
.AddApiEndpoints();
|
|
|
|
services.AddSingleton(TimeProvider.System);
|
|
services.AddTransient<IIdentityService, IdentityService>();
|
|
services.AddTransient<IStripeService, StripeService>();
|
|
|
|
services.AddAuthorization(options =>
|
|
options.AddPolicy(Policies.CanPurge, policy => policy.RequireRole(Roles.Administrator)));
|
|
|
|
return services;
|
|
}
|
|
}
|