Blazor WebAssembly - appsettings.json 作为注册服务时的依赖项 [英] Blazor WebAssembly - appsettings.json as dependency while registering services

查看:32
本文介绍了Blazor WebAssembly - appsettings.json 作为注册服务时的依赖项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将我的自定义 AppSettings 类注册为服务,但它不起作用,我迷路了.我有位于 wwwroot 的 AppSettings 类和相应的 appsettings.json 文件.然后我有另一个依赖于 AppSettings 类的类,ctor 看起来像这样:

I'm trying to register my custom AppSettings class as a service but it's not working and I'm lost. I have the AppSettings class and the corresponding appsettings.json file located at wwwroot. Then I have another class that depends on the AppSettings class, ctor looking like this:

public GeneratorService(AppSettings appSettings)
{
    _appSettings = appSettings;
}

Main 方法如下所示:

The Main method looks like this:

public static async Task Main(string[] args)
{
    var builder = WebAssemblyHostBuilder.CreateDefault(args);
    builder.RootComponents.Add<App>("app");
    builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
    builder.Services.AddTransient(async sp =>
        {
            var httpClient = sp.GetRequiredService<HttpClient>();
            var response = await httpClient.GetAsync("appsettings.json");
            using var json = await response.Content.ReadAsStreamAsync();
            return await JsonSerializer.DeserializeAsync<AppSettings>(json);
        }
    );
    builder.Services.AddTransient<GeneratorService>();
    await builder.Build().RunAsync();
}

我确信 JsonSerializer 从文件中创建了正确的 AppSettings 实例.我对此很陌生,但据我所知,它应该像这样工作:

I know for sure that the JsonSerializer creates the correct instance of AppSettings from the file. I'm pretty new to this but from what I understand, it should work like this:

  1. 我将 GeneratorService 注入到 .razor 页面,因此该页面需要 GeneratorService 实例
  2. GeneratorService 的构造函数中有 AppSettings,因此它要求提供 AppSettings 实例
  3. 服务提供者知道要获取 AppSettings 实例,它必须调用 HttpClient、读取和反序列化 appsettings.json 文件

但是当我尝试加载提到的 .razor 页面时,我收到此错误:

But when I try to load the mentioned .razor page, I'm getting this error:

Unhandled exception rendering component: Unable to resolve service for type 'BP.AppSettings' while attempting to activate 'BP.Services.GeneratorService'.

为什么服务提供者不能创建 AppSettings 并将其注入 GeneratorService 中?感谢您的回答.

How come that the service provider can't create AppSettings and inject it into the GeneratorService? Thank you for your answers.

推荐答案

example appsettings.json

example appsettings.json

{
  "ClientConfigurations": {
    "AzureAd": {
      "Authority": "https://login.microsoftonline.com/001f3bfc-XXXX-XXXX-XXX-17c0e6de3b0f",
      "ClientId": "815442365ec-xxxx-xxxx-xxxx-1ce9c3f3429",
      "ValidateAuthority": true
    }
  }
}

添加这些类.注意匹配的名称.

Add these classes. Note matching names.

    public class LocalConfigurations
    {
        public ClientConfigurations ClientConfigurations { get; set; }
    }
    public class ClientConfigurations
    {
        public AzureAdConfigurations AzureAd { get; set; }
    }
    public class AzureAdConfigurations
    {
        public string Authority { get; set; }
        public string ClientId { get; set; }
        public bool ValidateAuthority { get; set; }
    }

在 program.cs 中,它已经加载到 builder.Configuration 中.这两行应该可以帮助您访问它.

In program.cs it is already loaded into builder.Configuration. These two lines should help you access it.

var LocalConfigurations = builder.Configuration.Get<LocalConfigurations>();    
builder.Services.AddSingleton(LocalConfigurations.ClientConfigurations);

然后在任何组件中

@page "/"
@inject Models.ClientConfigurations config


@config.AzureAd.ClientId

这篇关于Blazor WebAssembly - appsettings.json 作为注册服务时的依赖项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆