How to resolve IOptions instance inside ConfigureServices?

If you need to resolve service using the service provider manually you can use this AddSingleton/AddScoped/AddTransient overload:

// Works for AddScoped and AddTransient as well
services.AddSingleton<IBarService>(sp =>
    var fooService = sp.GetRequiredService<IFooService>();
    return new BarService(fooService);

If you really want to, you can build an intermediate service provider using the BuildServiceProvider() method on the IServiceCollection:

public void ConfigureService(IServiceCollection services)
    // Configure the services
    services.AddTransient<IFooService, FooServiceImpl>();

    // Build an intermediate service provider
    var sp = services.BuildServiceProvider();

    // Resolve the services from the service provider
    var fooService = sp.GetService<IFooService>();
    var options = sp.GetService<IOptions<AppSettings>>();

You need the Microsoft.Extensions.DependencyInjection package for this.

However, please note that this results in multiple service provider instances which may in turn result in multiple singleton instances.

In the case where you just need to bind some options in ConfigureServices, you can also use the Bind method:

var appSettings = new AppSettings();

This functionality is available through the Microsoft.Extensions.Configuration.Binder package.

Leave a Comment