DEV Community

Cover image for Options Pattern
Abayomi Ogunnusi
Abayomi Ogunnusi

Posted on

4

Options Pattern

IOptions Pattern in ASP.NET Core in 4 Steps

This is a pattern that allows you to inject strongly typed configuration settings into your classes. It is a great way to keep your configuration settings in one place and to avoid having to use the IConfiguration interface directly in your classes.

How to use it

mkdir IOptionsPatternDemo
cd IOptionsPatternDemo
Enter fullscreen mode Exit fullscreen mode
Create a new ASP.NET Core Web Application
dotnet new webapi -o IOptionsPatternDemo
cd IOptionsPatternDemo
Enter fullscreen mode Exit fullscreen mode
Step 1. Create a new class called JwtSettings in the Models folder
 public class JwtSettings
    {
        public string Secret { get; set; } = string.Empty;

        public string Issuer { get; set; } = string.Empty;

        public string Audience { get; set; } = string.Empty;

        public int ExpirationInMinutes { get; set; } = 0;
    }
Enter fullscreen mode Exit fullscreen mode
Step 2. Add the following to the appsettings.json file
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "JwtSettings": {
    "Secret": "Damaam",
    "Issuer": "me",
    "Audience": "me",
    "ExpirationInMinutes": 90
  }
}
Enter fullscreen mode Exit fullscreen mode
Step 3. Add the following to the Program.cs file
using OptionsPattern.Models;

var builder = WebApplication.CreateBuilder(args);


builder.Services.Configure<JwtSettings>(builder.Configuration.GetSection("JwtSettings")); // <--- Add this line
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();
app.MapControllers();

app.Run();

Enter fullscreen mode Exit fullscreen mode
Create a new controller called UserController in the Controllers folder
  [ApiController]
    [Route("api/[controller]")]
    public class UserControllers : ControllerBase
    {
        private readonly IOptions<JwtSettings> _jwtSettings;

        public UserControllers(IOptions<JwtSettings> jwtSettings)
        {
            _jwtSettings = jwtSettings;
        }

        [HttpGet]
        public IActionResult Get()
        {
            return Ok(_jwtSettings.Value);
        }

        //GET A SPECIFIC VALUE
        [HttpGet("{key}")]
        public IActionResult Get(string key)
        {
            var value = _jwtSettings.Value.GetType().GetProperty(key)?.GetValue(_jwtSettings.Value, null);
            return Ok(value);
        }



    }
Enter fullscreen mode Exit fullscreen mode
Run the application
dotnet run
Enter fullscreen mode Exit fullscreen mode

Image description

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay