Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve IOptions instance inside ConfigureServices?

People also ask

How do you resolve IServiceCollection?

Resolve dependencies using IServiceProvider Once the container has been created, the IServiceCollection instance is composed into an IServiceProvider instance. You can use this instance to resolve services. You can inject an instance of type IServiceProvider into any method of a class.

How do I get an instance of IServiceProvider in .NET core?

An instance of IServiceProvider itself can be obtained by calling a BuildServiceProvider method of an IServiceCollection. IServiceCollection is a parameter of ConfigureServices method in a Startup class. It seems to be magically called with an instance of IServiceCollection by the framework.

Can I access a database during startup in asp net core?

Yes, you can access the database!


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>();
    services.Configure<AppSettings>(configuration.GetSection(nameof(AppSettings)));

    // 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();
configuration.GetSection(nameof(AppSettings)).Bind(appSettings);

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


The best way for instantiating classes that are dependent on other services is to use the AddXXX overload that provides you with the IServiceProvider. This way you do not need to instantiate an intermediate service provider.

The following samples show how you can use this overload in AddSingleton/AddTransient methods.

services.AddSingleton(serviceProvider =>
{
    var options = serviceProvider.GetService<IOptions<AppSettings>>();
    var foo = new Foo(options);
    return foo ;
});


services.AddTransient(serviceProvider =>
{
    var options = serviceProvider.GetService<IOptions<AppSettings>>();
    var bar = new Bar(options);
    return bar;
});

All of the other answers telling you to manually build an IServiceProvider to get an IOptions<T> instance are dangerous because they are wrong (at least as of ASP.NET Core 3.0)! In fact, if you use those answers today, you will get the following compiler warning:

Calling 'BuildServiceProvider' from application code results in an additional copy of singleton services being created. Consider alternatives such as dependency injecting services as parameters to 'Configure'.

The correct way is to accomplish this, which works safely and reliably in all versions of ASP.NET Core, is to implement the IConfigureOptions<TOptions> interface that's existed since .NET Core 1.0 - but it seems that far too few people know about how it makes things Just Work™.

As an example, you want to add a custom model validator that has a dependency on one of your application's other services. Initially it seems impossible - there's no way to resolve IMyServiceDependency because you have no access to an IServiceProvider:

public class MyModelValidatorProvider : IModelValidatorProvider
{
    public MyModelValidatorProvider(IMyServiceDependency dependency)
    {
        ...
    }
}

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers(options =>
    {
        options.ModelValidatorProviders.Add(new MyModelValidatorProvider(??????));
    });
}

But the "magic" of IConfigureOptions<TOptions> makes it so easy:

public class ConfigureMvcOptions : IConfigureOptions<MvcOptions>
{
    private IMyServiceDependency _dependency;

    public MyMvcOptions(IMyServiceDependency dependency)
        => _dependency = dependency;

    public void Configure(MvcOptions options)
        => options.ModelValidatorProviders.Add(new MyModelValidatorProvider(_dependency));
}

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();

    ...

    // or scoped, or transient, as necessary for your service
    services.AddSingleton<IConfigureOptions<MvcOptions>, ConfigureMvcOptions>();
}

Essentially, any setup you would have done in the Add***(***Options) delegates in ConfigureServices is now moved to your IConfigureOptions<TOptions> class's Configure method. Then you register the options in the same way you'd register any other service, and away you go!

For more detail, as well as information on how this works behind the scenes, I refer you to the always-excellent Andrew Lock.


Are you looking for something like following? You can take a look at my comments in the code:

// this call would new-up `AppSettings` type
services.Configure<AppSettings>(appSettings =>
{
    // bind the newed-up type with the data from the configuration section
    ConfigurationBinder.Bind(appSettings, Configuration.GetConfigurationSection(nameof(AppSettings)));

    // modify these settings if you want to
});

// your updated app settings should be available through DI now