grpc / grpc-dotnet

gRPC for .NET
Apache License 2.0
4.2k stars 769 forks source link

Using appsettings.{environment}.json in Program.cs (Blazor gRPC example) #849

Closed JeepNL closed 4 years ago

JeepNL commented 4 years ago

I'm using Blazor WebAssembly 3.2.0 Preview 3

I'm now using #if DEBUG #else #endif for the string variable "backendUrl". I'd like to load that setting from appsettings.{environment}.json. I can get that after var host = builder.Build(); (info from Microsoft Docs, see sample code below, and link here above) but the gRPC service is called before that.

My question: is it possible or should I keep using #if DEBUG etc. (I'd like to use appsettings whenever it is possible anywhere in my code.)

Part of my 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();
JamesNK commented 4 years ago

I don't know. Your question is about how Blazor works, and I haven't used it much.

You should ask at https://github.com/dotnet/aspnetcore/issues

JeepNL commented 4 years ago

Oops. Again.