'How to Get Environment in Blazor WebAssembly in Case Of Prerendering
I need to know Environment (Production/Development) in Blazor Component which is done through injecting IWebAssemblyHostEnvironment but when it run in Prerendering it gives me error that the sevices do not exists in Services. On other side we can get Environment through IWebHostEnvironment in Server Host which works in prerendering but give error in case of web assembly host (In Browser). Is there any services which work for both of Web Assembly Host (Browser) and Web Server Host (Server) or any other approach which we could conditionally base on server or web assembly host inject the right service to Blazor Component?
Thanks
Solution 1:[1]
I could handle both of the scenario in the following way.It needs to add Microsoft.AspNetCore.Hosting Nuget Package to Client side code which increased download size from 9.33 to 9.6 MB.
@using Microsoft.AspNetCore.Components.WebAssembly.Hosting
@using Microsoft.AspNetCore.Hosting
@inject IServiceProvider sp
@{
bool isProduction;
}
@if (sp.GetService<IWebAssemblyHostEnvironment>() is not null)
{
var env = sp.GetRequiredService<IWebAssemblyHostEnvironment>();
isProduction = env.IsProduction();
}
else
{
var env = sp.GetRequiredService<IHostingEnvironment>();
isProduction = env.IsProduction();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mehdi Mowlavi |
