问题
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?
回答1:
You should use the options pattern with strongly typed configuration:
- Create your
EmailSettings
strongly typed configuration class:
public class EmailSettings
{
public string HostName { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
- Update your appsettings.json to include a configuration section that maps to your
EmailSettings
configuration class:
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"EmailSettings": {
"HostName": "myhost.com",
"Username": "me",
"Password": "mysupersecretpassword",
}
}
- In the
ConfigureServices
call of yourStartup
class, bind appsettings.json to your config class
public void ConfigureServices(IServiceCollection services)
{
services.Configure<MySettings>(
options => Configuration.GetSection("EmailSettings").Bind(options));
}
- In your
AuthMessageSender
class, inject an instance ofIOptions<EmailSettings>
into the constructor
public 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"
}
}
回答2:
The recommended pattern is to read the specific config entries you need at startup and store them in an Options instance in DI, and inject that specific options type into your other components.
来源:https://stackoverflow.com/questions/38108400/asp-net-core-expose-config-to-di-injected-service