SHARE:

Simplified Options usage in ASP.NET Core 2+

Introduction

We all had at one time the need to have configuration data to consume some of them in our ASP.NET Core application.
In general we used the Options pattern as described in the Microsoft documentation. We will in this article see how to do slightly different to actually simplify the use of this pattern. The scenario below works only if your options will never change (singleton usage).

Configuration and suggested use in Microsoft Documentation

According to Microsoft documentation here the way to implement it:

appsetting.json:

SmtpConfiguration.cs:

Startup.cs:

DemoConfigController.cs:

Way to simplify usage

Now let’s make a little change.

We won’t use IOptions anymore in controllers / services / repositories, we will instead extract SmtpConfiguration object from IOptions<SmtpConfiguration> and inject it in controllers / services / repository as a singleton:

Now we can consume it in a simpler way:

Demo:

Simpler isn’t it? 😉

Written by

anthonygiretti

Anthony is a specialist in Web technologies (14 years of experience), in particular Microsoft .NET and learns the Cloud Azure platform. He has received twice the Microsoft MVP award and he is also certified Microsoft MCSD and Azure Fundamentals.