Problem statement
Bind the Smtp configuration section to a typed settings class with the options pattern, and give it to a service through its constructor.
Requirements
The SmtpSettings class, the EmailDispatcher methods and the SmtpController are already provided. Your task has two parts: bind the settings in SmtpSettingsApi/Program.cs, and write the constructor of EmailDispatcher in SmtpSettingsApi/Services/EmailDispatcher.cs.
With the options pattern, the app binds a configuration section to a class once. Any class that needs the values asks for IOptions<SmtpSettings> in its constructor, and Value holds the bound SmtpSettings.
appsettings.json already contains the section:
"Smtp": {
"Host": "smtp.fabrikam-mail.net",
"Port": 2525,
"FromAddress": "noreply@fabrikam.io",
"UseSsl": true,
"TimeoutSeconds": 45
}
Program.cs
- Bind the Smtp section (SmtpSettings.SectionName) to SmtpSettings with Configure, so IOptions<SmtpSettings> carries the values from the configuration. When a key in the section changes, the bound value changes with it
EmailDispatcher
- The constructor receives IOptions<SmtpSettings> and keeps its Value in the settings field
- The dispatcher reads its settings only from the injected options, never from IConfiguration
SmtpController (provided)
- GET /smtp/settings answers 200 with the five settings
- POST /email/preview answers 200 with a preview built from the settings. It answers 400 when to or subject is missing, or when to has no @
Sample Requests & Responses
GET /smtp/settings
Response (200 OK):
{
"host": "smtp.fabrikam-mail.net",
"port": 2525,
"fromAddress": "noreply@fabrikam.io",
"useSsl": true,
"timeoutSeconds": 45
}
POST /email/preview
Request body:
{ "to": "ops@contoso.com", "subject": "March invoice run" }
Response (200 OK):
{
"to": "ops@contoso.com",
"subject": "March invoice run",
"from": "noreply@fabrikam.io",
"host": "smtp.fabrikam-mail.net",
"port": 2525,
"useSsl": true,
"timeoutSeconds": 45,
"envelope": "noreply@fabrikam.io -> ops@contoso.com via smtp.fabrikam-mail.net:2525 [ssl=on, timeout=45s]"
}
POST /email/preview with { "to": "ops", "subject": "x" }
Response (400 Bad Request):
{ "error": "The to address must contain an @ sign." }
