I have a ASP.NET Core WebAPI project and I am trying to add configuration to my IEmailService
that I am injecting through DI like this:
services.AddTransient<IEmailSender, AuthMessageSender>();
How can instances of AuthMessageSender
get to settings in the config file?
You should use the options pattern with strongly typed configuration:
EmailSettings
strongly typed configuration class:public class EmailSettings
{
public string HostName { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
EmailSettings
configuration class:{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"EmailSettings": {
"HostName": "myhost.com",
"Username": "me",
"Password": "mysupersecretpassword",
}
}
ConfigureServices
call of your Startup
class, bind appsettings.json to your config classpublic void ConfigureServices(IServiceCollection services)
{
services.Configure<MySettings>(
options => Configuration.GetSection("EmailSettings").Bind(options));
}
AuthMessageSender
class, inject an instance of IOptions<EmailSettings>
into the constructorpublic class AuthMessageSender
{
private readonly EmailSettings _settings;
public AuthMessageSender(IOptions<EmailSettings> emailSettings)
{
_settings = emailSettings.Value;
// _settings.HostName == "myhost.com";
}
}
Note that in step 3, you can also use
public void ConfigureServices(IServiceCollection services)
{
services.Configure<MySettings>(Configuration.GetSection("EmailSettings"));
}
If you add a reference to Microsoft.Extensions.Options.ConfigurationExtensions in project.json:
{
"dependencies": {
"Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0"
}
}
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