Blazor WebAssembly 3.2.0 预览版 3 - 在 Program.cs 中使用 appsettings.{environment}.json

Blazor WebAssembly 3.2.0 Preview 3 - Using appsettings.{environment}.json in Program.cs

我正在使用 Blazor WebAssembly 3.2.0 预览版 3/静态/客户端

我现在使用 #if DEBUG #else #endif 作为字符串变量“backendUrl”。我想从 appsettings.{environment}.json 加载该设置。

我可以在 var host = builder.Build(); 之后获取配置(来自 Microsoft Docs 的信息,请参阅下面的示例代码,以及上面的 link)但是 gRPC 服务在此之前被调用。

More info 关于 appsetting.{environment}.json 在 Blazor WebAssembly 3.2.0 Preview 3

我的问题:我是否可以或应该继续使用 #if DEBUG
我想在我的代码中的任何地方尽可能使用 appsettings。 )

我的一部分Program.cs

    string backendUrl = string.Empty;
#if DEBUG
    backendUrl = "https://localhost:5001"; // Local debug URL
#else
    backendUrl = "https://<example>.com:5001"; // Production URL
#endif
    builder.Services.AddSingleton(services =>
    {
        // Create a gRPC-Web channel pointing to the backend server.
        // GrpcWebText is used because server streaming requires it. If server streaming is not used in your app
        // then GrpcWeb is recommended because it produces smaller messages.
        var httpClient = new HttpClient(new GrpcWebHandler(GrpcWebMode.GrpcWebText, new HttpClientHandler()));
        var channel = GrpcChannel.ForAddress(backendUrl, new GrpcChannelOptions { HttpClient = httpClient });
        return channel;
    });

    // load settings from appsettings.{environment}.json
    // see: https://docs.microsoft.com/en-us/aspnet/core/blazor/dependency-injection?view=aspnetcore-3.1#add-services-to-an-app
    var host = builder.Build();

    var backendDomain = host.Configuration["Settings:BackEndDomain"];
    Console.WriteLine($"Backend Domain: {backendDomain}");

    await host.RunAsync();

    // original
    // await builder.Build().RunAsync();

我也在 GitHub dotnet/aspnetcore 上发布了这个问题,James Newton-King 给出了答案,请参阅:https://github.com/dotnet/aspnetcore/issues/20442#issuecomment-608064432

JamesNK:

You should be able to get an IConfiguration inside the AddSingleton. e.g.

builder.Services.AddSingleton(services =>
{
    var configuration = services.GetRequiredService<IConfiguration>();
    var backendUrl = configuration["BackendUrl"];

    // Create a gRPC-Web channel pointing to the backend server.
    // GrpcWebText is used because server streaming requires it. If server streaming is not used in your app
    // then GrpcWeb is recommended because it produces smaller messages.
    var httpClient = new HttpClient(new GrpcWebHandler(GrpcWebMode.GrpcWebText, new HttpClientHandler()));
    var channel = GrpcChannel.ForAddress(backendUrl, new GrpcChannelOptions { HttpClient = httpClient });
    return channel;
});

根据 Jaap's 的回答,我必须为 Serilog BrowserHttp Sink 端点执行以下操作

services.AddSingleton(provider =>
        {
            var config = provider.GetService<IConfiguration>();
            _appConfiguration = config.GetSection("App").Get<AppConfiguration>();

            var levelSwitch = new LoggingLevelSwitch();
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.ControlledBy(levelSwitch)
                .Enrich.WithProperty("InstanceId", Guid.NewGuid().ToString("n"))
                .WriteTo.BrowserHttp(_appConfiguration.ApiBaseUrl, controlLevelSwitch: levelSwitch)
                .WriteTo.BrowserConsole()
                .CreateLogger();

            Log.Information("Hello, browser!");

            return _appConfiguration;
        });