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;
}
}