What is ioptions in. NET Core

Source: Internet
Author: User

I only found a use for ioptions-it's convenient to use strongly-typed configurations in. NET core applications.

If there is no ioptions, using a strongly-typed configuration requires that you resolve the following 2 issues yourself:

1) Deserialize the configuration in the configuration file (such as Appsettings.json) into an instance of the configuration class

2) Single example of injected configuration class

If you have ioptions, you can either pass configure<toptions> (iconfiguration config) or configure<toptions> (Action <TOptions> configureoptions) extension method to fix the above 2 questions at once.

Let's look at an example where we're going to be Ali greater than. NET client topsdk when migrating to. NET core, you want to implement configuring the client through Appsettings.json.

{"  topclient": {    "ServerURL": "",    "AppKey": "",    "Appsecret": "  "  }}

A configuration class topclientoptions is defined for this purpose:

 Public class topclientoptions{    publicstringgetset;}      Public string Get Set ; }      Public string Get Set ; }}

Then, by adding the following code to the startup Configureservices (), you can bind the configuration in Appsettings.json to the instance of Topclientoptions and complete the dependency injection.

Services. AddOptions ();
Services. Configure<topclientoptions> (Configuration.getsection ("topclient"));

(Note: Need to install NuGet package Microsoft.Extensions.Options.ConfigurationExtensions)

Only the constructor can be injected where you need to read the configuration in topclientoptions:

 Public class defaulttopclient:itopclient{    public defaulttopclient ( ioptions<topclientoptions>  Options)    {    }}

What is ioptions in. NET Core

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.