.NET 6 Blazor Server项目配置注入null项目

发布于 2025-02-02 05:43:51 字数 3365 浏览 2 评论 0原文

我是Blazor和.Net Core的新手,并试图弄清楚我缺少的东西。我的appSettings.development.json看起来像这样:

{
  "DetailedErrors": true,
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "RestServicesSettings": {
    "Url": "http://myurl.whatever",
    "UserName": "myusername",
    "Password": "mypassword"
  }
}

当我在本地运行应用程序时,我可以看到当我查看builder.configuration.cs.cs中时,它可以将配置作为源之一,这是IconFigurationRoot下的一个选项。提供者,如果我扩展了非公共成员,我可以从文件中看到数据。

在我的index.Razor页面上,我添加了以下几行:

@using Microsoft.Extensions.Configuration
@inject IConfiguration MyConfiguration

但是,当我调试应用程序时,字段myConfiguration为空。即使我让应用程序完全加载,它也永远不会变成无效(我确实注意到它击中了我设置了两次的断点,我知道当Blazor Server Apps加载时,这是预期的行为)。

我认为所有内容都应该自动连接起来,所以我不确定我缺少什么。我是根据生成新的Blazor Server应用程序来基于默认模板的。

我确实将以下调试代码添加到程序

var x = app.Configuration.GetSection("RestServicesSettings");

。 X是一个空对象。

我以为我正好遵循config di所需的步骤,但似乎缺少一些步骤。任何指针都将不胜感激。

编辑:下面是整个剃须刀组件。 myConfiguration!= null检查中的块从未达到。

@page "/"

@using MyAppNamespace.Data
@using MyAppNamespace.Services.Common
@using Microsoft.Extensions.Configuration
@inject IConfiguration MyConfiguration

<PageTitle>My Title</PageTitle>

<h1>Welcome Banner Text</h1>

Descriptive text

<br />

<EditForm Model="@loginRequest">
    <div>
        <b>Log In</b>
        <InputText DisplayName="UserName" @bind-Value="@loginRequest.UserName" id="UserName" />
        <br />
        <InputText DisplayName="Password" @bind-Value="@loginRequest.Password" id="Password" />
        <br />
        <button @onclick="PerformLogOn" value="Sign On" />
    </div>

</EditForm>

@code {

    private UserLogin loginRequest = new();
    private RestServicesOptions restServiceConfiguration = new();



    public Index()
    {

        if (MyConfiguration != null) {

            MyConfiguration.GetSection(RestServicesOptions.Setting)
            .Bind(restServiceConfiguration);

            Console.WriteLine(restServiceConfiguration.Url);
        }

    }

    private void PerformLogOn()
    {
        if(!string.IsNullOrEmpty(loginRequest.UserName) && !string.IsNullOrEmpty(loginRequest.Password))
        {
            
        } else
        {
            // Not provided
        }
    }

}

这是我的program.cs:

using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using MyAppNamespace.Data;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddOptions();

builder.Services.AddSingleton<WeatherForecastService>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

app.MapBlazorHub();

app.MapFallbackToPage("/_Host");

var x = app.Configuration.GetSection("RestServicesSettings");

app.Run();

I'm new to Blazor and .Net Core, and trying to figure out what I'm missing. My appsettings.Development.json looks like this:

{
  "DetailedErrors": true,
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "RestServicesSettings": {
    "Url": "http://myurl.whatever",
    "UserName": "myusername",
    "Password": "mypassword"
  }
}

When I run my application locally I can see that it picks up the configuration as one of the sources when I look at builder.Configuration in Program.cs - it's one of the options under IConfigurationRoot.Providers and if I expand the non-public members I can see the data from the file.

On my Index.razor page I have added the following lines:

@using Microsoft.Extensions.Configuration
@inject IConfiguration MyConfiguration

However, when I debug the app, the field MyConfiguration is null. It never becomes non-null even if I let the app completely load (I did note that it hits the breakpoint I have set twice, which I understand is expected behavior when Blazor server apps load).

I thought that everything was supposed to be wired up automatically so I'm not sure what I'm missing. I'm basing this off of the default template from generating a new Blazor server app.

I did add the following debug code to Program.cs:

var x = app.Configuration.GetSection("RestServicesSettings");

When I run the app, the value of app.Configuration is what I expect, and I see the contents of the config file through one of the non-public members, but the variable x is an empty object.

I thought I was following exactly the steps needed for config DI but something seems to be missing. Any pointers would be greatly appreciated.

Edit: Below is the entire Razor component. The block within the MyConfiguration != null check is never reached.

@page "/"

@using MyAppNamespace.Data
@using MyAppNamespace.Services.Common
@using Microsoft.Extensions.Configuration
@inject IConfiguration MyConfiguration

<PageTitle>My Title</PageTitle>

<h1>Welcome Banner Text</h1>

Descriptive text

<br />

<EditForm Model="@loginRequest">
    <div>
        <b>Log In</b>
        <InputText DisplayName="UserName" @bind-Value="@loginRequest.UserName" id="UserName" />
        <br />
        <InputText DisplayName="Password" @bind-Value="@loginRequest.Password" id="Password" />
        <br />
        <button @onclick="PerformLogOn" value="Sign On" />
    </div>

</EditForm>

@code {

    private UserLogin loginRequest = new();
    private RestServicesOptions restServiceConfiguration = new();



    public Index()
    {

        if (MyConfiguration != null) {

            MyConfiguration.GetSection(RestServicesOptions.Setting)
            .Bind(restServiceConfiguration);

            Console.WriteLine(restServiceConfiguration.Url);
        }

    }

    private void PerformLogOn()
    {
        if(!string.IsNullOrEmpty(loginRequest.UserName) && !string.IsNullOrEmpty(loginRequest.Password))
        {
            
        } else
        {
            // Not provided
        }
    }

}

And here is my Program.cs:

using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using MyAppNamespace.Data;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddOptions();

builder.Services.AddSingleton<WeatherForecastService>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

app.MapBlazorHub();

app.MapFallbackToPage("/_Host");

var x = app.Configuration.GetSection("RestServicesSettings");

app.Run();

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

没︽人懂的悲伤 2025-02-09 05:43:51
    public Index()
    {

        if (MyConfiguration != null) {

            MyConfiguration.GetSection(RestServicesOptions.Setting)
            .Bind(restServiceConfiguration);

            Console.WriteLine(restServiceConfiguration.Url);
        }

    }

构造函数注入在大麻组件中不起作用。您应该使用onInitialized {async}onParameterSset {async} 组件生命周期。值得注意的是,除了大麻零件外,依赖注入通常在C#文件中正常起作用,因为您可以使用(通过构造函数)。

public override void OnInitialized()
{

    if (MyConfiguration != null) {

        MyConfiguration.GetSection(RestServicesOptions.Setting)
        .Bind(restServiceConfiguration);

        Console.WriteLine(restServiceConfiguration.Url);
    }

}

作为建议,最好在构建的服务容器中进行.bind(),并且简单地注入ioptions&lt; restServicesOptions&gt;

    public Index()
    {

        if (MyConfiguration != null) {

            MyConfiguration.GetSection(RestServicesOptions.Setting)
            .Bind(restServiceConfiguration);

            Console.WriteLine(restServiceConfiguration.Url);
        }

    }

Constructor injection doesn't work this way in Blazor components. You should be using OnInitialized{Async} or OnParametersSet{Async} which are during the component lifecycle. It's worth noting that aside from blazor components, dependency injection works normally in C# files as you may be used to (via constructor).

public override void OnInitialized()
{

    if (MyConfiguration != null) {

        MyConfiguration.GetSection(RestServicesOptions.Setting)
        .Bind(restServiceConfiguration);

        Console.WriteLine(restServiceConfiguration.Url);
    }

}

As an recommendation, it would be better to do .Bind() during the service container being built and simply injecting IOptions<RestServicesOptions>.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文