Choosing between IConfiguration and IOptionsSnapshot in a .Net Core application

If you are building a .Net Core api and are using appsettings and/or Azure App configuration, you might have this question in mind. Since, this is the AI era, I keep asking my queries to chatgpt or copilot or bard and use my blog as the notes for myself and for my readers: Here is the prompt: What is the difference between IConfiguration and IOptionsSnapshot. When I am using Azure App Configuration in a .net core api what should I use out of the two? Let’s delve into the differences between  IConfiguration  and  IOptionsSnapshot , especially in the context of using Azure App Configuration in a .NET Core API. IConfiguration: Purpose :  IConfiguration  provides access to configuration settings (such as app settings, connection strings, etc.) from various sources (e.g., JSON files, environment variables, command-line arguments). Lifetime : It is a singleton service, meaning it retrieves configuration values once during application startup and caches them. Use Case : Suitable when you don’

Resolved Error - Azure Powershell failed to get token from Token Cache. Getting You cannot call a method on a null-valued expression

 Recently, I was working on an Azure Powershell Script in which I was getting the Cached Token and it was working fine for a long time and it started failing recently.

Here is the code that I was using in my powershell script:

    Write-Host "Getting Az Context"
    $azContext = Get-AzContext
    Write-Host "Displaying context"

    #$rmAccount = Add-AzureRmAccount -SubscriptionId $subscriptionId 
    #$tenantId = $azureRmContext.Tenant.Id
    $tokenCache = $azContext.TokenCache
    $cachedTokens = $tokenCache.ReadItems() `
        #| where { $_.TenantId -eq $tenantId } `
        Sort-Object -Property ExpiresOn -Descending
	
    $cachedTokens[0].AccessToken
  

Now, I started getting the error "You cannot call a method on a null-valued expression". I was clear that my Token Cache is getting expired and then I googled about the issue and I find the following useful github links: And finally, I implemented the following solution:

Solution:

    $currentAzureContext = Get-AzContext
    $azureRmProfile = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile;
    $profileClient = New-Object Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient($azureRmProfile);
    $profileClient.AcquireAccessToken($currentAzureContext.Subscription.TenantId).AccessToken;