Blazor WebAssembly - appsettings.json 在注册服务时作为依赖项

Blazor WebAssembly - appsettings.json as dependency while registering services

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

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

Main 方法如下所示:

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 实例。我对此很陌生,但据我了解,它应该像这样工作:

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

但是当我尝试加载提到的 .razor 页面时,出现了这个错误:

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

为什么服务提供者无法创建AppSettings并将其注入GeneratorService? 谢谢你的回答。

示例appsettings.json

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

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

    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 中。 这两行应该可以帮助您访问它。

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

然后在任何组件中

@page "/"
@inject Models.ClientConfigurations config


@config.AzureAd.ClientId

我是 Blazor 的新手,但是如果你在 root 中有一个 appsettings.json,例如

{
  "message": "Hello word"
}

只要在你的服务中注入IConfiguration,所以

public WeatherForecastClient(HttpClient client, IConfiguration Configuration)
{
     Console.WriteLine(Configuration["message"]);
     this.client = client;
}

Dane Vinson's this entry 中,您有另一种方法,它将“appsettings.json”作为嵌入式资源嵌入。

1.-将文件放在 Blazor 客户端项目的根目录下

2.-编辑你的 project.csproj 并添加一些类似的

  <ItemGroup>
    <EmbeddedResource Include="your-file.json">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </EmbeddedResource>
  </ItemGroup>

3.-创建一个 .json 和一个 class SettingsInfo

4.-在program.cs中添加服务

public static async Task Main(string[] args)
{
    //fileName is NameOf your Assembly.your-file.json, e.g.
    string fileName = "Blazor1.Client.appsettings.json";
    var stream = Assembly.GetExecutingAssembly()
                         .GetManifestResourceStream(fileName);

    var config = new ConfigurationBuilder()
            .AddJsonStream(stream)
            .Build();

    builder.Services.AddTransient(_ =>
    {
        return config.GetSection("AppSettings")
                     .Get<SettingsInfo>();
    });

    ....
 }

现在您可以在 razor 页面或服务中注入 SettingsInfo

谢谢你们的回答。阅读 Orak 的回答后,我决定将我的 AppSettings 实例注册为单例,现在它可以工作了。所以代替:

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

我只有:

var response = await client.GetAsync("appsettings.json");
using var json = await response.Content.ReadAsStreamAsync();
var appSettings = await JsonSerializer.DeserializeAsync<AppSettings>(json);
builder.Services.AddSingleton(appSettings);

我想将 AppSettings 作为单例而不是瞬态更有意义。我仍然不确定为什么我的原始代码不起作用。

编辑: 使用配置也有效:

var appSettings = builder.Configuration.Get<AppSettings>();
builder.Services.AddSingleton(appSettings.NamesLists);