Blazor: Managing Environment Specific Variables
appsettings are now supported in blazor directly so you can inject it: https://devblogs.microsoft.com/aspnet/blazor-webassembly-3-2-0-preview-3-release-now-available/
You can create singleton with configuration interface and inject it in you components.
.csproj
<ItemGroup>
<EmbeddedResource Include="appsettings.Development.json" Condition="'$(Configuration)' == 'Debug'">
<LogicalName>appsettings.json</LogicalName>
</EmbeddedResource>
<EmbeddedResource Include="appsettings.json" Condition="'$(Configuration)' == 'Release'">
<LogicalName>appsettings.json</LogicalName>
</EmbeddedResource>
</ItemGroup>
Startup.cs
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton(GetConfiguration());
}
private IConfiguration GetConfiguration()
{
// Get the configuration from embedded dll.
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("appsettings.json"))
using (var reader = new StreamReader(stream))
{
return JsonConvert.DeserializeObject<IConfiguration>(reader.ReadToEnd());
}
}
MyComponent.razor
@inject Configuration.IConfiguration Configuration;
Or look this issue
There are multiple ways use can do this,
I believe there is no any official method documented yet!
My recommendation is to use the good old method, using multiple config files for different environments and copying only the config files to be used in the intended environemnt.
Create a folder called env in the solution folder. and create sub folders called dev and prod. like below.
|- env
|- dev
|- prod
|
Place your different config files (file with same name and different configs) inside dev and prod folders.
Create a batch file to copy appropreate environment to wwwroot
folder. (I prefer this than the next step since, this is much CI friendly , no need to install Visual Studio in build server)
OR
add the below code to the post-build event
of the Blazor Project
if $(ConfigurationName) == Debug (
copy /Y "$(ProjectDir)env\dev\*" "$(TargetDir)\wwwroot"
) ELSE (
copy /Y "$(ProjectDir)env\prod\*" "$(TargetDir)\wwwroot"
)
Since your config file is in the www folder you can easily refer this from the blazor app by opening the file and reading whats inside this.
My solution was creating the 3 corresponding files in the root project solution
- appsettings.json
- appsettings.Debug.json
- appsettings.Release.json
then in pre-build event of your project replace the correct file to wwwroot directory
if $(ConfigurationName) == Debug (
copy /Y "$(ProjectDir)appsettings.Debug.json" "$(TargetDir)..\..\..\wwwroot\appsettings.json") ELSE (
copy /Y "$(ProjectDir)appsettings.Release.json" "$(TargetDir)..\..\..\wwwroot\appsettings.json" )