Skip to content

Commit ef88a96

Browse files
authored
Enhance the Options config example (#34459)
1 parent ef5ed24 commit ef88a96

File tree

1 file changed

+56
-2
lines changed

1 file changed

+56
-2
lines changed

aspnetcore/blazor/fundamentals/configuration.md

Lines changed: 56 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -315,9 +315,63 @@ For more information on how background updates are handled by PWAs, see <xref:bl
315315

316316
Example:
317317

318+
`OptionsExample.cs`:
319+
320+
```csharp
321+
public class OptionsExample
322+
{
323+
public string? Option1 { get; set; }
324+
public string? Option2 { get; set; }
325+
}
326+
```
327+
328+
In `appsettings.json`:
329+
330+
```json
331+
"OptionsExample": {
332+
"Option1": "Option1 Value",
333+
"Option2": "Option2 Value"
334+
}
335+
```
336+
318337
```csharp
319-
builder.Services.Configure<MyOptions>(
320-
builder.Configuration.GetSection("MyOptions"));
338+
builder.Services.Configure<OptionsExample>(
339+
builder.Configuration.GetSection("OptionsExample"));
340+
```
341+
342+
The following Razor component retrieves the settings with the [`@inject`](xref:mvc/views/razor#inject) directive or [`[Inject]` attribute](xref:Microsoft.AspNetCore.Components.InjectAttribute).
343+
344+
`Options.razor`:
345+
346+
```razor
347+
@page "/options"
348+
@using Microsoft.Extensions.Options
349+
@inject IOptions<OptionsExample>? OptionsExample1
350+
351+
<h1>Options</h1>
352+
353+
<h2>
354+
&commat;inject approach
355+
</h2>
356+
357+
<ul>
358+
<li>@OptionsExample1?.Value.Option1</li>
359+
<li>@OptionsExample1?.Value.Option2</li>
360+
</ul>
361+
362+
<h2>
363+
[Inject] approach
364+
</h2>
365+
366+
<ul>
367+
<li>@OptionsExample2?.Value.Option1</li>
368+
<li>@OptionsExample2?.Value.Option2</li>
369+
</ul>
370+
371+
@code {
372+
[Inject]
373+
public IOptions<OptionsExample>? OptionsExample2 { get; set; }
374+
}
321375
```
322376

323377
Not all of the ASP.NET Core Options features are supported in Razor components. For example, <xref:Microsoft.Extensions.Options.IOptionsSnapshot%601> and <xref:Microsoft.Extensions.Options.IOptionsMonitor%601> configuration is supported, but recomputing option values for these interfaces isn't supported outside of reloading the app by either requesting the app in a new browser tab or selecting the browser's reload button. Merely calling [`StateHasChanged`](xref:blazor/components/lifecycle#state-changes-statehaschanged) doesn't update snapshot or monitored option values when the underlying configuration changes.

0 commit comments

Comments
 (0)