✅ How to get Options from DI
I configured options for google authentication
CliendId
and ClientSecret
.
Here I want to get them from ServiceProvider
but I don't know how. Should I create ServiceProvider
var provider = builder.Services.BuildServiceProvider();
?
8 Replies
using google credentials is a little more involved than that, because depending on the flow you are using you could be reading credentials from environment, from a json file, or even somewhere else
you should really follow a tutorial for this, imho
The MSFT docs for the IOptions<T> pattern are really good, and will answer the general question "How do I use/obtain IOptions<T> from DI?" sufficiently.
If your question is more about the google credentials specifically, that's an appropriate question for a thread like this imo.
My question is how can I get options that I configured above exactly in .AddGoogle()?
I don't know what
.AddGoogle()
does or where it comes from. But unless it calls .AddOptions<T>
and then either
or
Then the options haven't been configured.
This all assumes you want to bind the options to some values in your configuration. As we mentioned above, this topic does necessitate some understanding so reading the MSFT docs here truly is your best bet.
This is an example of how to bind a config class and register it as an Option in your app. When you then create a class and add IOptions<SpotifyConfig>
to its parameter list, the DI container will inject that for you.
The next immediate question is "but where does it get the values from?" to which the answer is go read the MSFT docs, it'll explain it all in detail 🙂dont do BuildServiceProvider cuz calling it from application code results in an additional copy of singleton services being created
the easiest way is to use builder.Congifuration to get your properties
or you can do
Btw $options
appsettings.json:
src/Foo/FooOptions.cs:
src/Foo/FooServiceCollectionExtensions.cs:
Program.cs / Startup.cs:
Bar.cs:
Thank you for the answers