Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NetCore IOptions configure object with constructor

In a .NetCore application I want to inject into a service a setting that has some custom logic in the constructor. In particular, I have a setting section looking similar to this:

"Email": {
    "FromEmailName" : "My name",
    "FromEmail" : "[email protected]"
}

Now, I'd like to bind this to a class looking like:

public class EmailSettings {
    public System.Net.Mail.MailAddress MailAddress { get; } 
 
    public EmailSetting(string fromEmailName, string fromEmail) {
        MailAddress = new MailAddress(fromEmail, fromEmailName);
    }
}

From the docs I see that the EmailSettings class must have a parameterless constructor, but is there any way that I can overcome this problem by introducing an 'intermediate' class UnparsedEmailSetting, and then do something like the code below?

public static void BindEmailConfig(this IServiceCollection services, IConfiguration configuration) {
    var section = configuration.GetSection("Email");
    services.Configure<UnparsedEmailSettings>(section);
    var emailConfig = section.Get<UnparsedEmailSettings>();
    var emailSettings = new 
    EmailSettings(emailConfig.FromEmailName, emailConfig.FromEmail);
    services.Configure<EmailSettings>(emailSetting); // does not work
    services.RemoveConfiguration<UnparsedEmailSettings); // method does not exist
}
like image 996
SimonAx Avatar asked Sep 12 '25 21:09

SimonAx


1 Answers

Since adding an option basically means adding a singleton of type IOptions<TOptions>, you can do that. There is no constructor for Options, but you can use the create method from the Options extensions.

services.AddSingleton<IOptions<EmailSetting>>(serviceProvider =>
{
    return Options.Create(new EmailSetting(Configuration.GetSection("Email").GetSection("FromEmailName").Value,
                    Configuration.GetSection("Email").GetSection("FromEmail").Value));
});

It can then be injected as usual with IOptions<EmailSetting>.

like image 191
Jakob Avatar answered Sep 16 '25 02:09

Jakob