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