在@code - .net Core Blazor 中访问@Inject 变量

Access @Inject variable in @code - .net Core Blazor

我是 Blazor .net Core 的新手。我在我的 .razor 页面中注入了服务设置

@inject Microsoft.Extensions.Options.IOptions<Configuration> Configuration

接下来我有下面的 @code 指令来初始化 _m 对象

@code 
{
    private ViewModel _m = new ViewModel(Configuration.Value);

    protected async Task DoSearchAsync()
    {
        await _m.PerformSearchAsync();
    }
}

ConfigureServices中注册代码:

services.Configure<Configuration>(options => 
    Configuration.GetSection("ConfigurationSettings").Bind(options));

Configuration.cs

public class Configuration
{
    private string ServiceEndpointUrl { get; set; }
}

我需要将配置传递给采用 IOptions<T>ViewModel() 构造函数,但由于某些原因,我无法在 @code 指令中访问我注入的变量 "Configuration"。请问如何访问?

您可以在如下方法中访问注入的服务:

@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();
    }
}