How to configure custom object from JSON string?

178 Views Asked by At

I would like to use a system environment variable that contains my smtp settings configuration JSON to configure my custom SmtpSettings object at startup.

This is my actual working code that retrieve the configuration from secrets/appsettings.json:

//Configure email service for DI
services.Configure<SmtpSettings>(Configuration.GetSection("SmtpSettings"));
services.AddSingleton<IMailService, MailService>();

I would like to obtain something like this:

services.Configure<SmtpSettings>(Environment.GetEnvironmentVariable("SMTP_SETTINGS") ?? Configuration.GetSection("SmtpSettings"));

I need to use the system environment variable if available, else use the standard configuration contained on secrets/appsettings.json.

How can I obtain the desired implementation?

1

There are 1 best solutions below

0
Vivekh On

I guess you can do something like this in the

var envVar = Environment.GetEnvironmentVariable("SMTP_SETTINGS");
            if (string.IsNullOrEmpty(envVar))
            {
                services.Configure<SMTP_SETTINGS>(Configuration.GetSection("SMTP_SETTINGS"));
            }
            else
            {
                services.Configure<SMTP_SETTINGS>(options =>
                {
                    var smtpSettings = JsonConvert.DeserializeObject<SMTP_SETTINGS>(envVar);
                    options.Host = smtpSettings.Host;
                    options.Port = smtpSettings.Port;
                });
            }

If you are passing the environment variable as something below

"SMTP_SETTINGS":"{"Port": 567, "Host": "smtp.com"}"