Dotnet core custom configuration file, dotnetcore

Source: Internet
Author: User

Dotnet core custom configuration file, dotnetcore

First, add a. json file. For example, the content of the setting. json file is as follows. Remember to set the file to "Copy to output directory"

{
"ConfigSetting ":{
"XXXName": "Name ",
"XXXValue": "Value"
}
}

 

Define an acceptance Model

Public class SettingModel
{
Public string XXXName {get; set ;}

Public string XXXValue {get; set ;}
}

In the Startup. cs method, add the following registration event to public void ConfigureServices (IServiceCollection services ).

Services. Configure <SettingModel> (Configuration. GetSection ("ConfigSetting "));

 

Then it can be used normally in the task Controller or service. The usage can be found in the red section below:

Public class SyncService: IBaseService
{

Private readonly System. Timers. Timer _ timer;
Private readonly ILogger logger;
Private readonly SettingModel settingModel;
Public SyncService (IOptions <SettingModel> settingOptons, ILoggerFactory loggerFactory)
{
This. settingModel = settingOptons. Value;
_ Timer = new System. Timers. Timer (10000 );
_ Timer. Elapsed + = new ElapsedEventHandler (OnTimedEvent );

_ Timer. Interval = 2000;

_ Timer. AutoReset = true;
_ Timer. Enabled = false;
Logger = loggerFactory. CreateLogger <SyncService> ();
}


Private void OnTimedEvent (object source, ElapsedEventArgs e)
{
Console. WriteLine (string. Format ("SyncService: {0: yyyy-MM-dd HH: mm: sss}", DateTime. Now ));
_ Timer. Enabled = false;

Try
{
// Do some job;
}
Catch (Exception ex)
{
Logger. LogError ("SyncService Error {0}:", ex. Message );
}
Console. WriteLine (string. Format ("SyncService: {0: yyyy-MM-dd HH: mm: sss}", DateTime. Now ));

Thread. Sleep (5x60*1000 );

_ Timer. Enabled = true;

}

Public void Start ()
{
_ Timer. Start ();
_ Timer. Enabled = true;
}
Public void Stop ()
{
_ Timer. Stop ();
_ Timer. Enabled = false;
}
}

Related Article

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.