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
}
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>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With