Gabriel Anton
Gabriel Anton

Reputation: 624

.NET 5 IOptionsSnapshot: Cannot resolve scoped service

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
  }
}

Upvotes: 9

Views: 5883

Answers (2)

Jensen
Jensen

Reputation: 1329

When consuming IOptions<> from a singleton and you want to make use of automatic config reloads, you should use IOptionsMonitor<> instead of IOptionsSnapshot<> as advised here: https://github.com/dotnet/aspnetcore/issues/2380#issuecomment-358505218

Upvotes: 1

Kirk Larkin
Kirk Larkin

Reputation: 93123

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>>();

   //...
}

Upvotes: 19

Related Questions