You are currently viewing Utilising the .Net Options Pattern to Enhance Configuration Management

Utilising the .Net Options Pattern to Enhance Configuration Management

public class ServiceHost

{

   public string Host { get; set; }

    public int Port { get; set; }

}

public class ServiceCredentials

{

    public string Username { get; set; }

    public string Password { get; set; }

}

public class EmailServiceOptions

{

    public ServiceHost Host { get; set; }

    public ServiceCredentials Credentials { get; set; }

    public string SenderEmail { get; set; }

    public string SenderName { get; set; }

}

public class FTPServiceOptions

{

    public ServiceHost Host { get; set; }

    public ServiceCredentials Credentials { get; set; }

    public string Directory { get; set; }

}

public class EmailServiceOptions

{

    [Required]

    public ServiceHost Host { get; set; }

    [Required]

    public ServiceCredentials Credentials { get; set; }

    [Required]

    [EmailAddress]

    public string SenderEmail { get; set; }

}

services.AddOptions<EmailServiceOptions>()

         .Bind(Configuration.GetSection(“EmailSettings”))

             .ValidateDataAnnotations();

public class FTPServiceOptions

{

    public ServiceHost Host { get; set; }

    public ServiceCredentials Credentials { get; set; }

    public string Directory { get; set; }

    public string[] PermittedOperations { get; set; }

}

    “FTPSettings”:

    {

         “Host”: “ftp.example.com”,

         “Port”: 21,

         “Username”: “ftpuser”,

         “Password”: “ftppassword”,

         “Directory”: “/uploads”,

         “PermittedOperations”: [ “read”, “write”, “delete” ]

  }

  • Abstraction: Abstracts app settings from specific providers, using the general IConfiguration built by the dependency injection pattern.
  • Flexibility: Allows for easy nesting of classes and support for inheritance.
  • Validation: Supports data validation attributes to ensure the integrity of settings.

Leave a Reply