How to read the configuration in a. NET Core class Library project in Appsettings.json

Source: Internet
Author: User

This is a friend asked me a question, write an essay to answer. There are 2 methods, one called the Ugly method--iconfiguration, a kind of elegant method--ioptions.

1) Look at the ugly way first

For example, in redisclient, you need to read the Redis connection string in Appsettings.json:

{"  Redis": {    "ConnectionString": "XXX"  }}

The IConfiguration interface needs to be added to the Redisclient constructor parameter and read directly through it:

 Public class redisclient{    privatereadonlystring  _connectionstring;      Public redisclient (iconfiguration configuration)    {        = configuration. GetSection ("redis") ["ConnectionString"] ;    }}

Then inject in the Startup configureservices () method:

 Public Get ; }  Public void configureservices (iservicecollection services) {    services. Addsingleton<IConfiguration>(Configuration);     }

2) Then look at the elegant method

First define a configuration class redisoptions that holds the connection string:

 Public class redisoptions{    publicstringgetset;}

The ioptions<redisoptions> interface is then added to the constructor parameters of Redisclient, and the ioptions<redisoptions> reads the configuration, Redisclient does not care Appsettings.json:

 Public class redisclient{    privatereadonly  redisoptions _redisoptions;      Public Redisclient (ioptions<redisoptions> redisoptions)    {        = redisoptions.value;    }}

The configuration in Appsettings.json can be injected into the Startup configureservices ():

Services. AddOptions (); services. Configure<RedisOptions> (configuration.getsection ("redis"));

(Note: Use the Configure method above to install the NuGet package Microsoft.Extensions.Options.ConfigurationExtensions)

As the designer of the class library, you can be more intimate and write an extension method to do the above injection.

How to read the configuration in a. NET Core class Library project in Appsettings.json

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.