.NET 5 IOptionsSnapshot: Cannot resolve scoped service

Viewed 1745

I get the following Exception when I try to resolve the IOptionsSnapshot service:

'Cannot resolve scoped service 'Microsoft.Extensions.Options.IOptionsSnapshot`1[Test.MyOptions]' from root provider.'

I leave the test code down below, if someone can tell me the problem.

Main

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("AppSettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile("MyOptions.json", optional: false, reloadOnChange: true)
            .AddEnvironmentVariables()
            .Build();

        var services = new ServiceCollection();
        var provider = services.Configure<MyOptions>(configuration.GetSection(nameof(MyOptions))).BuildServiceProvider(true);

        var test = provider.GetRequiredService<IOptionsSnapshot<MyOptions>>();
    }
}

MyOptions class

public class MyOptions
{
    public int Value { get; set; }
}

MyOptions.json

{
  "MyOptions": {
    "Value": 10
  }
}
1 Answers

IOptionsSnapshot<T> is registered as a scoped service, which means you need to create a service scope and then resolve using that:

using (var scope = provider.CreateScope())
{
    var scopedProvider = scope.ServiceProvider;
    var test = scopedProvider.GetRequiredService<IOptionsSnapshot<MyOptions>>();

   //...
}
Related