DEV Community

Ahmed Shah
Ahmed Shah

Posted on

Enhancing Data Validation in .NET IOptions Pattern: Utilizing Named and Typed IOptions for Robust Configuration.

Continuing the series All About IOptions Pattern in .NET. link
In this last post we have talked about Introduction to IOptions Pattern in .NET. link.

In this post we will learn about

  • Named and Typed IOptions
  • Validation in IOptions Pattern

What is Named and Typed IOptions in .NET
In our previous post we were using Typed IOptions in our project. which is used when we have single configuration for our properties as you can see in this code below we have single company configuration in our appsettings.json.

Image

In program.cs we binding this appsettings configuration to our class using Typed IOptions since we have only one company settings in our appsettings file.

Image

What about having multiple companies settings in our appsettings file and binding them to our CompanyOptions Class for this purpose we need to used Named IOptions in out program file. lets add some more companies in appsettings.

Image
as you can see we have 2 company types in our appsettings now. CoOperate and Invidual. let try to bind them with our CompanyOPtions class and modify it.

Image

In program.cs we also need to change the bindings from Typed to Named IOptions.

Image

all the changes have been made now lets access them in our controller.

Image

let run the project using IOptionsSnapshot and see the results.

Image description
we can see each company settings have been matched with their respective class using named options pattern. For IOptions we need to create two different classes because it binds its settings at compile time.
Code Link of GitHub link
In the next series we will learn about Validation in IOptions Pattern.

Top comments (0)