How to Resolve Instance Inside ConfigureServices i

2019-01-17 06:07发布

问题:

Is it possible to resolve an instance of IOptions<AppSettings> from the ConfigureServices method in Startup? Normally you can use IServiceProvider to initialize instances but you don't have it at this stage when you are registering services.

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<AppSettings>(
        configuration.GetConfigurationSection(nameof(AppSettings)));

    // How can I resolve IOptions<AppSettings> here?
}

回答1:

You can build a 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.


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.



回答2:

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