Software_Engineering_Field_.../SiteManagementSystem(Softwa.../Extension/IServiceCollectionExtension.cs

63 lines
2.6 KiB
C#
Raw Normal View History

2024-11-03 11:21:47 +08:00
using SiteManagementSystem_SoftwareEngineering_.Configuration;
2024-10-30 17:52:22 +08:00
using SiteManagementSystem_SoftwareEngineering_.Factory;
using SiteManagementSystem_SoftwareEngineering_.Interface;
using SiteManagementSystem_SoftwareEngineering_.Model;
2024-10-30 17:52:22 +08:00
using SiteManagementSystem_SoftwareEngineering_.Service;
using static SiteManagementSystem_SoftwareEngineering_.Service.UserManagerService;
namespace SiteManagementSystem_SoftwareEngineering_.Extension
{
public static class IServiceCollectionExtension
{
public static IServiceCollection AddTokenFactory(
this IServiceCollection services,
Action<TokenFactoryConfiguration> options
)
{
var config = new TokenFactoryConfiguration();
options(config);
if (config.Audience is null)
throw new ArgumentNullException(nameof(config.Audience) + "can not be null.");
if (config.Issuer is null)
throw new ArgumentNullException(nameof(config.Issuer) + "can not be null.");
if (config.SigningKey is null)
throw new ArgumentNullException(nameof(config.SigningKey) + "can not be null.");
services.AddScoped<ITokenFactory, TokenFactory>(_ => new TokenFactory(config));
return services;
}
public static IServiceCollection AddUserManager(
this IServiceCollection services,
Action<SecretConfig> options
)
2024-10-30 17:52:22 +08:00
{
var config = new SecretConfig();
options(config);
if (config.HashSalt is null)
throw new ArgumentNullException(nameof(config.HashSalt) + "can not be null");
2024-10-30 17:52:22 +08:00
services.AddScoped<IUserManageService, UserManageService>(services =>
{
var logger = services.GetRequiredService<ILogger<UserManageService>>();
var storageService = services.GetRequiredService<SQLService>();
2024-10-30 17:52:22 +08:00
return new UserManageService(storageService, logger, config.HashSalt);
});
return services;
}
public static IServiceCollection AddRedisUtils(
this IServiceCollection services,
Action<RedisConfig> options
)
{
var config = new RedisConfig();
options(config);
if (config.RedisConnectionString is null)
throw new ArgumentNullException("Redis ConnectionString is null.");
services.AddSingleton<RedisUtils>(services =>
new RedisUtils(config.RedisConnectionString, config.RedisDB, services.GetRequiredService<ILogger<RedisUtils>>())
);
return services;
}
2024-10-30 17:52:22 +08:00
}
}