Simplified Options usage in ASP.NET Core 2+
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:
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:
Simpler isn’t it? 😉