I am new to Blazor .net Core. I have injected service settings in my .razor page
@inject Microsoft.Extensions.Options.IOptions<Configuration> Configuration
Next I have @code
directive below that initialise the _m object
@code
{
private ViewModel _m = new ViewModel(Configuration.Value);
protected async Task DoSearchAsync()
{
await _m.PerformSearchAsync();
}
}
Registered code in ConfigureServices:
services.Configure<Configuration>(options =>
Configuration.GetSection("ConfigurationSettings").Bind(options));
Configuration.cs
public class Configuration
{
private string ServiceEndpointUrl { get; set; }
}
I need to pass the Configuration to ViewModel()
constructor that takes IOptions<T>
, but for some reason I cannot access my injected variable "Configuration" in @code
directive. How do I access that please?
You can access your injected Service inside a method like:
@inject Microsoft.Extensions.Options.IOptions<Configuration> cfg
@code {
private ViewModel _m;
protected override void OnInitialized()
{
base.OnInitialized();
_m = new ViewModel(cfg.Value);
}
protected async Task DoSearchAsync()
{
await _m.PerformSearchAsync();
}
}