Configuring the email service

Nearly all of the services you create in the future will have some kind of configuration, which should be configurable from the outside of your code.

ASP.NET Core 3 has a built-in Configuration API for this purpose. It provides various functionalities for reading configuration data from multiple sources during application runtime. Name-value pairs, which can be grouped into multi-level hierarchies, are used for configuration data persistence. Furthermore, the configuration data can be automatically deserialized into Plain Old CLR Objects (POCO), which contain private members and properties.

The following configuration sources are supported by ASP.NET Core 3:

  • Configuration files (JSON, XML, and even classic INI files)
  • Environment variables
  • Command-line arguments
  • In-memory .NET objects
  • Encrypted user stores
  • Azure Key Vault
  • Custom providers
For more information about the Configuration API, please visit https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration?tabs=basicconfiguration.

Let's learn how to make the email service quickly configurable by using the ASP.NET Core 3 Configuration API with a JSON configuration file:

  1. Add a new appsettings.json configuration file to the project and add the following custom section. This will be used to configure the email service:
        "Email": { 
          "MailType": "SMTP", 
          "MailServer": "localhost", 
          "MailPort": 25, 
          "UseSSL": false, 
          "UserId": "", 
          "Password": "", 
          "RemoteServerAPI": "", 
          "RemoteServerKey": "" 
        } 
  1. In the Solution Explorer, create a new folder called Options at the root of the project. Add a new POCO class called EmailServiceOptions to this folder and implement some private members, as well as public properties, for the options we saw previously:
public class EmailServiceOptions 
{ 
  private string MailType { get; set; } 
  private string MailServer { get; set; } 
  private string MailPort { get; set; } 
  private string UseSSL { get; set; } 
  private string UserId { get; set; } 
  private string Password { get; set; } 
  private string RemoteServerAPI { get; set; } 
  private string RemoteServerKey { get; set; } 
 
  public EmailServiceOptions()  {  } 
 
  public EmailServiceOptions(string mailType, string mailServer, 
string mailPort, string useSSL,
string userId, string password, string
remoteServerAPI,string remoteServerKey) { MailType = mailType; MailServer = mailServer; MailPort = mailPort; UseSSL = useSSL; UserId = userId; Password = password; RemoteServerAPI = remoteServerAPI; RemoteServerKey = remoteServerKey; }
}
  1. Update the EmailService implementation, add EmailServiceOptions, and add a parameterized constructor to the class:
        private EmailServiceOptions _emailServiceOptions; 
        public EmailService(IOptions<EmailServiceOptions> 
emailServiceOptions) { _emailServiceOptions = emailServiceOptions.Value; }
  1. Add a new constructor to the Startup class so that you can configure your email service:
        public IConfiguration _configuration { get; } 
        public Startup(IConfiguration configuration) 
        { 
          _configuration = configuration; 
        } 
  1. Update the ConfigureServices method of the Startup class:
        services.Configure<EmailServiceOptions>
(_configuration.GetSection("Email")); services.AddSingleton<IEmailService, EmailService>();

  1. Update the SendEmail method in EmailService. Use the email service options to retrieve the settings from the configuration file, as shown here:
        public Task SendEmail(string emailTo, string
subject, string message) { using (var client =
new SmtpClient(_emailServiceOptions.MailServer,
int.Parse(_emailServiceOptions.MailPort))) { if (bool.Parse(_emailServiceOptions.UseSSL) ==
true)client.EnableSsl = true; if (!string.IsNullOrEmpty(_emailServiceOptions.UserId)) client.Credentials =
new NetworkCredential(_emailServiceOptions.UserId,
_emailServiceOptions.Password); client.Send(new MailMessage("[email protected]",
emailTo, subject, message)); } return Task.CompletedTask; }
  1. Put a breakpoint into the EmailService constructor and start the application in debug mode by pressing F5. Now, verify that the email service options values have been retrieved correctly from the configuration file. If you have an SMTP server, you can also verify that the email has really been sent:

In this section, you have learned how to configure your applications and services by using the built-in Configuration API of ASP.NET Core 3, which allows you to write less code and be much more productive, all while providing a far more elegant and more maintainable solution.

Another feature of ASP.NET Core 3 that helps us have maintainable code is its intrinsic dependency injection (DI) capabilities. Among other advantages, DI ensures that we don't have too much coupling between classes. We'll have a look at DI in the context of ASP.NET Core 3 in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.31.206