Get appsettings.json values in service .net core

蹲街弑〆低调 提交于 2019-12-05 21:40:53

You should register Configuration in ConfigureServices:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddSingleton<IConfiguration>(Configuration);
}

You can see my code here for detail. Basically I want to read email setting and the structure of my email setting look like this

"EmailSettings": {
    "MailServer": "",
    "MailPort": "",
    "Email": "",
    "Password": "",
    "SenderName": "",
    "Sender": "",
    "SysAdminEmail": ""
  }

Then I will need to define a class like this to hold all of information in appSetting

 public class EmailSettings
    {
        public string MailServer { get; set; }
        public int MailPort { get; set; }
        public string SenderName { get; set; }
        public string Sender { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
        public string SysAdminEmail { get; set; }
    } 

Finally I inject into my service class or whatever you want

private readonly IOptions<EmailSettings> _emailSetting;

public EmailSender(IOptions<EmailSettings> emailSetting)
{
    _emailSetting = emailSetting;
}

then call

var something = _emailSetting.Value.SenderName

Email sender file can be found here

If you have any question just let me know.

** Note this example help you read appSetting inside service class like class library or we can access appsetting data from outside main mvc app.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!