Skip to content

Commit fcc1956

Browse files
authored
Reduce IOptions usage (#237)
1 parent 74cc4b1 commit fcc1956

28 files changed

+171
-217
lines changed

API/Controller/Account/Login.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,10 @@ public sealed partial class AccountController
2828
[MapToApiVersion("1")]
2929
public async Task<IActionResult> Login(
3030
[FromBody] Login body,
31-
[FromServices] IOptions<FrontendOptions> options,
31+
[FromServices] FrontendOptions options,
3232
CancellationToken cancellationToken)
3333
{
34-
var cookieDomainToUse = options.Value.CookieDomain.Split(',').FirstOrDefault(domain => Request.Headers.Host.ToString().EndsWith(domain, StringComparison.OrdinalIgnoreCase));
34+
var cookieDomainToUse = options.CookieDomains.FirstOrDefault(domain => Request.Headers.Host.ToString().EndsWith(domain, StringComparison.OrdinalIgnoreCase));
3535
if (cookieDomainToUse is null) return Problem(LoginError.InvalidDomain);
3636

3737
var loginAction = await _accountService.CreateUserLoginSessionAsync(body.Email, body.Password, new LoginContext

API/Controller/Account/LoginV2.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,10 +33,10 @@ public sealed partial class AccountController
3333
public async Task<IActionResult> LoginV2(
3434
[FromBody] LoginV2 body,
3535
[FromServices] ICloudflareTurnstileService turnstileService,
36-
[FromServices] IOptions<FrontendOptions> options,
36+
[FromServices] FrontendOptions options,
3737
CancellationToken cancellationToken)
3838
{
39-
var cookieDomainToUse = options.Value.CookieDomain.Split(',').FirstOrDefault(domain => Request.Headers.Host.ToString().EndsWith(domain, StringComparison.OrdinalIgnoreCase));
39+
var cookieDomainToUse = options.CookieDomains.FirstOrDefault(domain => Request.Headers.Host.ToString().EndsWith(domain, StringComparison.OrdinalIgnoreCase));
4040
if (cookieDomainToUse is null) return Problem(LoginError.InvalidDomain);
4141

4242
var remoteIP = HttpContext.GetRemoteIP();

API/Controller/Account/Logout.cs

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,25 +14,23 @@ public sealed partial class AccountController
1414
[MapToApiVersion("1")]
1515
public async Task<IActionResult> Logout(
1616
[FromServices] ISessionService sessionService,
17-
[FromServices] IOptions<FrontendOptions> options)
17+
[FromServices] FrontendOptions options)
1818
{
19-
var config = options.Value;
20-
2119
// Remove session if valid
2220
if (HttpContext.TryGetUserSessionToken(out var sessionToken))
2321
{
2422
await sessionService.DeleteSessionByTokenAsync(sessionToken);
2523
}
2624

2725
// Make sure cookie is removed, no matter if authenticated or not
28-
var cookieDomainToUse = config.CookieDomain.Split(',').FirstOrDefault(domain => Request.Headers.Host.ToString().EndsWith(domain, StringComparison.OrdinalIgnoreCase));
26+
var cookieDomainToUse = options.CookieDomains.FirstOrDefault(domain => Request.Headers.Host.ToString().EndsWith(domain, StringComparison.OrdinalIgnoreCase));
2927
if (cookieDomainToUse is not null)
3028
{
3129
HttpContext.RemoveSessionKeyCookie("." + cookieDomainToUse);
3230
}
3331
else // Fallback to all domains
3432
{
35-
foreach (var domain in config.CookieDomain.Split(','))
33+
foreach (var domain in options.CookieDomains)
3634
{
3735
HttpContext.RemoveSessionKeyCookie("." + domain);
3836
}

API/Controller/Version/_ApiController.cs

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -38,22 +38,19 @@ private static string GetBackendVersion()
3838
/// <response code="200">The version was successfully retrieved.</response>
3939
[HttpGet]
4040
public LegacyDataResponse<BackendInfoResponse> GetBackendInfo(
41-
[FromServices] IOptions<FrontendOptions> frontendOptions,
42-
[FromServices] IOptions<TurnstileOptions> turnstileOptions
41+
[FromServices] FrontendOptions frontendOptions,
42+
[FromServices] TurnstileOptions turnstileOptions
4343
)
4444
{
45-
var frontendConfig = frontendOptions.Value;
46-
var turnstileConfig = turnstileOptions.Value;
47-
4845
return new(
4946
new BackendInfoResponse
5047
{
5148
Version = OpenShockBackendVersion,
5249
Commit = GitHashAttribute.FullHash,
5350
CurrentTime = DateTimeOffset.UtcNow,
54-
FrontendUrl = frontendConfig.BaseUrl,
55-
ShortLinkUrl = frontendConfig.ShortUrl,
56-
TurnstileSiteKey = turnstileConfig.SiteKey,
51+
FrontendUrl = frontendOptions.BaseUrl,
52+
ShortLinkUrl = frontendOptions.ShortUrl,
53+
TurnstileSiteKey = turnstileOptions.SiteKey,
5754
IsUserAuthenticated = HttpContext.TryGetUserSessionToken(out _)
5855
},
5956
"OpenShock"

API/Program.cs

Lines changed: 9 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
using Microsoft.AspNetCore.Http.Connections;
2-
using Microsoft.Extensions.Options;
32
using OpenShock.API.Realtime;
4-
using OpenShock.API.Services;
53
using OpenShock.API.Services.Account;
64
using OpenShock.API.Services.DeviceUpdate;
75
using OpenShock.API.Services.Email;
@@ -11,7 +9,6 @@
119
using OpenShock.Common.DeviceControl;
1210
using OpenShock.Common.Extensions;
1311
using OpenShock.Common.Hubs;
14-
using OpenShock.Common.Options;
1512
using OpenShock.Common.Services;
1613
using OpenShock.Common.Services.Device;
1714
using OpenShock.Common.Services.LCGNodeProvisioner;
@@ -21,23 +18,16 @@
2118

2219
var builder = OpenShockApplication.CreateDefaultBuilder<Program>(args);
2320

24-
#region Config
25-
26-
builder.RegisterCommonOpenShockOptions();
27-
28-
builder.Services.Configure<FrontendOptions>(builder.Configuration.GetRequiredSection(FrontendOptions.SectionName));
29-
builder.Services.AddSingleton<IValidateOptions<FrontendOptions>, FrontendOptionsValidator>();
30-
31-
var databaseConfig = builder.Configuration.GetDatabaseOptions();
32-
var redisConfig = builder.Configuration.GetRedisConfigurationOptions();
33-
34-
#endregion
21+
var redisOptions = builder.RegisterRedisOptions();
22+
var databaseOptions = builder.RegisterDatabaseOptions();
23+
builder.RegisterMetricsOptions();
24+
builder.RegisterFrontendOptions();
3525

3626
builder.Services
37-
.AddOpenShockMemDB(redisConfig)
38-
.AddOpenShockDB(databaseConfig)
27+
.AddOpenShockMemDB(redisOptions)
28+
.AddOpenShockDB(databaseOptions)
3929
.AddOpenShockServices()
40-
.AddOpenShockSignalR(redisConfig);
30+
.AddOpenShockSignalR(redisOptions);
4131

4232
builder.Services.AddScoped<IDeviceService, DeviceService>();
4333
builder.Services.AddScoped<IControlSender, ControlSender>();
@@ -60,9 +50,9 @@
6050

6151
await app.UseCommonOpenShockMiddleware();
6252

63-
if (!databaseConfig.SkipMigration)
53+
if (!databaseOptions.SkipMigration)
6454
{
65-
await app.ApplyPendingOpenShockMigrations(databaseConfig);
55+
await app.ApplyPendingOpenShockMigrations(databaseOptions);
6656
}
6757
else
6858
{

API/Services/Account/AccountService.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,12 +35,12 @@ public sealed class AccountService : IAccountService
3535
/// <param name="logger"></param>
3636
/// <param name="options"></param>
3737
public AccountService(OpenShockContext db, IEmailService emailService,
38-
ISessionService sessionService, ILogger<AccountService> logger, IOptions<FrontendOptions> options)
38+
ISessionService sessionService, ILogger<AccountService> logger, FrontendOptions options)
3939
{
4040
_db = db;
4141
_emailService = emailService;
4242
_logger = logger;
43-
_frontendConfig = options.Value;
43+
_frontendConfig = options;
4444
_sessionService = sessionService;
4545
}
4646

API/Services/Email/EmailServiceExtension.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ public static WebApplicationBuilder AddEmailService(this WebApplicationBuilder b
3636

3737
private static WebApplicationBuilder AddSenderContactConfiguration(this WebApplicationBuilder builder)
3838
{
39-
builder.Services.Configure<MailOptions.MailSenderContact>(builder.Configuration.GetRequiredSection(MailOptions.SenderSectionName));
39+
builder.Services.AddSingleton(builder.Configuration.GetRequiredSection(MailOptions.SenderSectionName).Get<MailOptions.MailSenderContact>() ?? throw new NullReferenceException());
4040
return builder;
4141
}
4242
}

API/Services/Email/Mailjet/MailjetEmailService.cs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@ public sealed class MailjetEmailService : IEmailService, IDisposable
1111
{
1212
private readonly HttpClient _httpClient;
1313
private readonly MailJetOptions _options;
14-
private readonly ILogger<MailjetEmailService> _logger;
1514
private readonly MailOptions.MailSenderContact _sender;
15+
private readonly ILogger<MailjetEmailService> _logger;
1616

1717
/// <summary>
1818
/// DI Constructor
@@ -23,14 +23,14 @@ public sealed class MailjetEmailService : IEmailService, IDisposable
2323
/// <param name="logger"></param>
2424
public MailjetEmailService(
2525
HttpClient httpClient,
26-
IOptions<MailJetOptions> options,
27-
IOptions<MailOptions.MailSenderContact> sender,
26+
MailJetOptions options,
27+
MailOptions.MailSenderContact sender,
2828
ILogger<MailjetEmailService> logger
2929
)
3030
{
3131
_httpClient = httpClient;
32-
_sender = sender.Value;
33-
_options = options.Value;
32+
_options = options;
33+
_sender = sender;
3434
_logger = logger;
3535
}
3636

API/Services/Email/Mailjet/MailjetEmailServiceExtension.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,11 @@ public static WebApplicationBuilder AddMailjetEmailService(this WebApplicationBu
1111
{
1212
var section = builder.Configuration.GetRequiredSection(MailJetOptions.SectionName);
1313

14+
15+
// TODO Simplify this
1416
builder.Services.Configure<MailJetOptions>(section);
1517
builder.Services.AddSingleton<IValidateOptions<MailJetOptions>, MailJetOptionsValidator>();
18+
builder.Services.AddSingleton<MailJetOptions>(sp => sp.GetRequiredService<IOptions<MailJetOptions>>().Value);
1619

1720
var options = section.Get<MailJetOptions>() ?? throw new NullReferenceException("MailJetOptions is null!");
1821
var basicAuthValue = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{options.Key}:{options.Secret}"));

API/Services/Email/Smtp/SmtpEmailService.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@ namespace OpenShock.API.Services.Email.Smtp;
1313
public sealed class SmtpEmailService : IEmailService
1414
{
1515
private readonly SmtpServiceTemplates _templates;
16-
private readonly MailboxAddress _sender;
1716
private readonly SmtpOptions _options;
17+
private readonly MailboxAddress _sender;
1818
private readonly ILogger<SmtpEmailService> _logger;
1919

2020
private readonly TemplateOptions _templateOptions;
@@ -24,19 +24,19 @@ public sealed class SmtpEmailService : IEmailService
2424
/// DI Constructor
2525
/// </summary>
2626
/// <param name="templates"></param>
27-
/// <param name="sender"></param>
2827
/// <param name="options"></param>
28+
/// <param name="sender"></param>
2929
/// <param name="logger"></param>
3030
public SmtpEmailService(
3131
SmtpServiceTemplates templates,
32-
IOptions<MailOptions.MailSenderContact> sender,
3332
IOptions<SmtpOptions> options,
33+
MailOptions.MailSenderContact sender,
3434
ILogger<SmtpEmailService> logger
3535
)
3636
{
3737
_templates = templates;
38-
_sender = sender.Value.ToMailAddress();
3938
_options = options.Value;
39+
_sender = sender.ToMailAddress();
4040
_logger = logger;
4141

4242
// This class is will be registered as a singleton, static members are not needed

0 commit comments

Comments
 (0)