You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

165 lines
5.7 KiB

using CellularManagement.Infrastructure.Context;
using CellularManagement.Infrastructure.Options;
using CellularManagement.Infrastructure.Repositories;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using CellularManagement.Domain.Entities;
using CellularManagement.Domain.Repositories;
using CellularManagement.Infrastructure.Services;
using Scrutor;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using CellularManagement.Infrastructure.Configurations;
using CellularManagement.Domain.Services;
namespace CellularManagement.Infrastructure;
/// <summary>
/// 依赖注入扩展方法
/// </summary>
public static class DependencyInjection
{
/// <summary>
/// 添加基础设施服务
/// </summary>
/// <param name="services">服务集合</param>
/// <param name="configuration">配置</param>
/// <returns>服务集合</returns>
public static IServiceCollection AddInfrastructure(
this IServiceCollection services,
IConfiguration configuration)
{
ArgumentNullException.ThrowIfNull(services);
ArgumentNullException.ThrowIfNull(configuration);
var assembly = typeof(DependencyInjection).Assembly;
var databaseOptions = configuration
.GetSection(DatabaseOptions.SectionName)
.Get<DatabaseOptions>();
if (databaseOptions is null)
{
throw new ArgumentNullException(
nameof(databaseOptions),
"Database options not configured");
}
// 添加 JWT 服务
services.AddJwtServices(configuration);
// 添加邮箱服务
services.Configure<EmailOptions>(configuration.GetSection(EmailOptions.SectionName));
services.AddScoped<IEmailService, EmailService>();
services.AddScoped<IEmailVerificationService, EmailVerificationService>();
// 配置数据库选项
services.Configure<DatabaseOptions>(configuration.GetSection(DatabaseOptions.SectionName));
var databaseOptionsConfig = configuration.GetSection(DatabaseOptions.SectionName).Get<DatabaseOptions>();
if (databaseOptionsConfig?.DefaultConnection is null)
{
throw new ArgumentNullException(
nameof(databaseOptionsConfig.DefaultConnection),
"Database connection string not configured");
}
// 配置数据库上下文
services.AddDbContext<AppDbContext>(options =>
{
// 使用 PostgreSQL 数据库
options.UseNpgsql(
databaseOptionsConfig.DefaultConnection,
sqlOptions =>
{
// 配置重试策略
sqlOptions.EnableRetryOnFailure(3);
// 配置命令超时时间
sqlOptions.CommandTimeout(databaseOptionsConfig.CommandTimeout);
});
// 配置详细错误信息
if (databaseOptionsConfig.EnableDetailedErrors)
{
options.EnableDetailedErrors();
}
// 配置敏感数据日志记录
if (databaseOptionsConfig.EnableSensitiveDataLogging)
{
options.EnableSensitiveDataLogging();
}
});
// 配置身份认证服务
services
.AddIdentityCore<AppUser>()
.AddRoles<AppRole>()
.AddEntityFrameworkStores<AppDbContext>();
// 注册工作单元
services.AddScoped<IUnitOfWork, UnitOfWork>();
// 注册通用仓储
services.AddScoped(typeof(ICommandRepository<>), typeof(CommandRepository<>));
services.AddScoped(typeof(IQueryRepository<>), typeof(QueryRepository<>));
// 注册权限仓储
services.AddScoped<IPermissionRepository, PermissionRepository>();
// 添加内存缓存
services.AddMemoryCache();
// 添加分布式缓存
services.AddDistributedMemoryCache();
// 注册缓存服务
services.AddScoped<ICacheService, CacheService>();
// 配置认证设置
services.Configure<AuthConfiguration>(configuration.GetSection("Auth"));
// 自动注册服务
services
.Scan(action =>
{
action
.FromAssemblies(assembly)
.AddClasses(false)
.UsingRegistrationStrategy(RegistrationStrategy.Skip)
.AsImplementedInterfaces()
.WithScopedLifetime();
});
return services;
}
/// <summary>
/// 添加 JWT 服务
/// </summary>
/// <param name="services">服务集合</param>
/// <param name="configuration">配置</param>
/// <returns>服务集合</returns>
private static IServiceCollection AddJwtServices(
this IServiceCollection services,
IConfiguration configuration)
{
// 配置 JWT 选项
var jwtOptions = configuration.GetSection(JwtOptions.SectionName).Get<JwtOptions>();
if (jwtOptions == null)
{
throw new InvalidOperationException("JWT配置未找到");
}
services.Configure<JwtOptions>(configuration.GetSection(JwtOptions.SectionName));
// 注册 JWT 服务
services.AddSingleton<IConfigureOptions<JwtBearerOptions>, JwtBearerOptionsSetup>();
services.AddScoped<IJwtProvider, JwtProvider>();
services.AddSingleton<IKeyRotationService, KeyRotationService>();
services.AddHostedService<KeyRotationBackgroundService>();
return services;
}
}