Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core Expose Config to DI Injected Service

I have a ASP.NET Core WebAPI project and I am trying to add configuration to my IEmailServicethat I am injecting through DI like this:

services.AddTransient<IEmailSender, AuthMessageSender>();

How can instances of AuthMessageSender get to settings in the config file?

like image 480
Zeus82 Avatar asked Jun 29 '16 19:06

Zeus82


1 Answers

You should use the options pattern with strongly typed configuration:

  1. 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; }
}
  1. 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",
  }
}
  1. In the ConfigureServices call of your Startup class, bind appsettings.json to your config class
public void ConfigureServices(IServiceCollection services)  
{
    services.Configure<MySettings>(
          options => Configuration.GetSection("EmailSettings").Bind(options));
}
  1. In your AuthMessageSender class, inject an instance of IOptions<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"
  }
}
like image 129
Sock Avatar answered Sep 21 '22 18:09

Sock