Configurationbuilder This class provides configuration bindings, Webhost provides default bindings (appsettings files) in the DNC program
If we need to load our own JSON config file how to handle
var New Configurationbuilder ();
Builder here provides a lot of ways to add
1, the first kind: Directly add the JSON file path, here need to pay attention to the JSON file address problem
Builder. Addjsonfile ("path"). Build ();
2. The second type
Builder. ADD ("instance of Iconfigurationsource ")
Builder. ADD (new"websiteconfig.json"falsetrue }). Bind ();
Set up the corresponding JSON file corresponding to the Entity model class
Configure the service inside:
Services. Configure<websiteconfig> (Configuration); // Configuration
For example, the database connection string configuration processing, or the system fixed configuration, here I expanded the next Npoco service extension add
Services. Addnpococontext (Options = = configuration.get<websiteconfig>(). ConnectionStr; });
How to get this configuration in the business layer or at other levels in the system
An interface that needs to be used here ioptions
Add injection-related classes in the service
Services. AddOptions ();
For example, a model class that injects related ioptions into our test class
PrivateIoptions<npocodatabasesetting>_options; PrivateIoptions<websiteconfig>_website; Privateitestrepository _testservices; PrivateITransaction _transaction; PublicTestservices (IServiceProvider serviceprovider, ioptions<npocodatabasesetting> options, ITransaction Transaction, ioptions<websiteconfig>website, itestrepository testservices) {_options=options; _testservices=testservices; _transaction=transaction; _website=website; }
Such as:
Ioptions<websiteconfig> _website, we can pass
/// <summary> ///Test Get Data/// </summary> /// <returns></returns> PublicList<test>GetData () {stringWebName =_website. Value.webname; List<Test> list =NewList<test>(); Try{_transaction. Begin (); List=_testservices.test (); _transaction.commit (); } Catch(Exception) {_transaction. RollBack (); } returnlist; }
Get to WebName, here is noteworthy JSON file Chinese garbled problem, to determine the JSON file encoding type UTF-8
The DNC reads the configuration JSON file into the class and uses it in the program