Clean Configuration with the IOptions Pattern

Osama HaiDer
2 min readApr 6, 2024

--

Say goodbye to confusion and chaos in your code’s settings. Meet the IOptions pattern — a simple way to keep your .NET Core apps organized.

Imagine your settings neatly packed in a single class called AppSettings. Each setting has its own spot in this class. Easy to find, easy to manage.

Here’s how it works:

  1. Create Your AppSettings Class: Think of it as a home for all your settings.
public class AppSettings
{
public string AppName { get; set; }
public string AppVersion { get; set; }
}

2. Inject Your Settings: With the IOptions pattern, you can inject your settings wherever you need them.

private readonly AppSettings _appSettings;

public ApplicationController(IOptions<AppSettings> appSettings)
{
_appSettings = appSettings.Value;
}

3. Fetch Your Settings: Want to grab a setting? It’s as easy as pie.

[HttpGet("GetAppData")]
public IActionResult GetAppData()
{
var appName = _appSettings.AppName;
var appVersion = _appSettings.AppVersion;

var appData = "App Name: " + appName + " And App Version: " + appVersion;
return Ok(appData);
}

4. Set Your Configuration: Just put your settings in a nice little JSON file.

"AppSettings": {
"AppName": "BookLoan",
"AppVersion": "1.0.0"
}

And Yesss! Your settings are neatly organized, easy to access, and simple to understand.

With the IOptions pattern, complexity fades away, and clarity takes the stage. Keep your codebase clean and clear — start using the IOptions pattern today!

👉 [GitHub Repository]

For more updates and insights, and to connect with me, feel free to follow me on LinkedIn:

🔗 [Connect on LinkedIn]

Let’s stay connected and continue the conversation! 🚀

--

--

Osama HaiDer
Osama HaiDer

Written by Osama HaiDer

SSE at TEO International | .Net | Azure | AWS | Web APIs | C#

No responses yet