2015-08-06 20 views
17

IOptions<AppSettings> örneğini, Başlangıç'ta ConfigureServices yönteminden çözümlemek mümkün mü? Normal olarak, örnekleri başlatmak için IServiceProvider'u kullanabilirsiniz, ancak hizmetleri kaydettirirken bu aşamada bulunmazsınız.ASP.NET Çekirdeğinde ConfigureServices İçinde Örnek Nasıl Çözümlenir

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

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

cevap

26

Sen IServiceCollection üzerinde BuildServiceProvider() yöntemi kullanarak bir servis sağlayıcı inşa edebilirsiniz:

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

Bunun için Microsoft.Extensions.DependencyInjection paket lazım.

var appSettings = new AppSettings(); 
configuration.GetSection(nameof(AppSettings)).Bind(appSettings); 

Bu işlevsellik Microsoft.Extensions.Configuration.Binder paketin içinden mevcuttur:


sadece ConfigureServices bazı seçenekler bağlamak gerekiyor durumda, ayrıca Bind yöntemi kullanabilirsiniz.

+0

Bu hizmeti, uygulamanın başka bir bölümünde çözmeniz gerekiyorsa? Eminim her şey ConfigureServices() içinde doğru değil mi? – Ray

+0

@Ray sonra kurucu enjeksiyon gibi varsayılan bağımlılık enjeksiyon mekanizmalarını kullanabilirsiniz. Bu soru, özellikle 'ConfigureServices' yönteminin içindeki hizmetlerin çözümüyle ilgilidir. –

1

Aşağıdaki gibi bir şey mi arıyorsunuz? Sen kodunda benim Yorumlarına göz atabilirsiniz:

// 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 
İlgili konular