❔ ASP.NET Core Environment Variables in Dependency Injection
Hello, I have a (probably) slightly dumb question.
What's the correct/recommended way to inject an environment variable (like from docker-compose or similar) into a service class in ASP.NET Core?
Googling somehow always points me toward "multiple environments" such as test/staging/prod, but that's not what I'm looking for.
My hunch is that I'm supposed to do it in
Program.cs
when setting up DI, somehow.
In Spring I might do something like this to inject MY_ENV_VAR
as a String
into MyService
11 Replies
I guess you are heading in the wrong direction
You need it as a configuration?
Anything in environment can be read through the IConfiguration
Then you would need Microsoft.Extensions.Configuration
And you can inhect either a strongly-typed binded Options object or directly IConfiguration
IOptions, yes
Thx for correcting
Yeah, I ended up with something like this
builder.Services.Configure<XsdPackageServiceOptions>(builder.Configuration.GetSection("XsdPackageServiceOptions"));
Which is then defined in appsettings.Development.json
although I haven't yet tested if actual OS environment variables would affect this at allDepends on your configuration setup, if you do something like .AddJsonFile().AddEnvironmentVariables() or use default host builder then you are probably fine
You can add env vars in your IDE to test things
Unknown User•16mo ago
Message Not Public
Sign In & Join Server To View
appsettings.json:
src/Foo/FooOptions.cs:
src/Foo/FooServiceCollectionExtensions.cs:
Program.cs / Startup.cs:
Bar.cs:
Unknown User•16mo ago
Message Not Public
Sign In & Join Server To View
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.