K.Z
K.Z

Reputation: 5075

In .NET Core, how to read from appsetting.json and assign value to object in setter method

I have SendGrid Email config in appsettings.json that I need to initialise in startup.cs, I have define class EmailConfig where I want to assign values from appsettings.json so that I can use else where.

appsetting.json

"SendGridEmailSettings": {
    "SendGrid_API_Key": "MY-Key-XYZ",
    "From": "[email protected]"

}

EmailConfig class

  public class EmailConfig : IEmailConfig
{
    public string API_Key { get; set; }
    public string From { get; set; }
}

In my core class I need to read this value as

public mailConfig emailConfig { get; set; } 

Upvotes: 0

Views: 215

Answers (1)

MarioMendieta
MarioMendieta

Reputation: 312

I would first rename the EmailConfig fields to match the settings:

public class EmailConfig
{
    public string SendGrid_API_Key { get; set; }
    public string From { get; set; }
}

In the ConfigureServices method in your startup.cs, add:

var emailConfig = new EmailConfig();
Configuration.GetSection("SendGridEmailSettings").Bind(emailConfig);

At this point, the emailConfig object has the appsetting.json values.

If I may suggest, I would then create a service dedicated to sending out emails, and pass the EmailConfig object to the service once:

public class EmailService : IEmailService
{
    private readonly EmailConfig _emailConfig;

    public EmailService(EmailConfig emailConfig)
    {
        _emailConfig = emailConfig
    }
}

You can now send the emailConfig object to the service by adding the following in the ConfigureServices method in your startup.cs:

services.AddTransient<IEmailService, EmailService>(_ =>
    new EmailService(emailConfig));

Upvotes: 3

Related Questions