Skip to content

IOptionsSnapshot can return empty value #37860

@vladar107

Description

@vladar107

I've try to test IOptions and his friends and find some strange behaviour

Simple Web API

With appsetings.json
Controller returns settings value

    private readonly IOptionsSnapshot _optionsSnapshot;

    public SettingsController(IOptionsSnapshot optionsSnapshot, IScopedService scopedService,
        ITransientService transientService)
    {
        _optionsSnapshot = optionsSnapshot;
    }
    [HttpGet]
    public string Get()
    {
        return _optionsSnapshot.Value.Test.ToString();
    }

Client

    static async Task Main(string[] args)
    {
        using var client = new HttpClient();
        var prevResponse = String.Empty;
        while (true)
        {
            var response = await client.GetStringAsync("http://localhost:5010/settings");
            if (response != prevResponse)
            {
                Console.WriteLine(response);
                prevResponse = response;
            }
        }
    }

After start i get next result

    ScopedService IOptionsSnapshot value: 0

After changing settings value

    ScopedService IOptionsSnapshot value: // it's empty
    ScopedService IOptionsSnapshot value: changed setting // next log, value was changed

Problems

Why is it empty at first time?
If we compare with IOptionMonitor - on first call it has old value, on second call it has empty value too, and we have third call where value was changed.

Full version of this example here

Environment

sw_vers                                                              
ProductName:	Mac OS X
ProductVersion:	10.15.5
BuildVersion:	19F101

dotnet --version                                                          
3.1.301

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-Extensions-OptionsbugquestionAnswer questions and provide assistance, not an issue with source code or documentation.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions