是否可以IOptions<AppSettings>从ConfigureServicesStartup中的方法解析实例?通常,您可以使用IServiceProvider初始化实例,但在注册服务时此阶段没有实例.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(
configuration.GetConfigurationSection(nameof(AppSettings)));
// How can I resolve IOptions<AppSettings> here?
}
Run Code Online (Sandbox Code Playgroud) 我正在开发 .Net Core Web 应用程序,并在 Startup.cs 上安装并配置了 IdentityServer4,这里我从已在 IOC 中注册的服务加载令牌签名证书:
builder.AddSigningCredential(services.BuildServiceProvider().
GetService<ISecretStoreService>().
TokenSigningCertificate().Result);
Run Code Online (Sandbox Code Playgroud)
完整代码如下:
public void ConfigureServices(IServiceCollection services)
{
//....
var builder = services.AddIdentityServer(options =>
{
options.IssuerUri = Configuration.GetValue<string>("IdSrv:IssuerUri"); ;
options.PublicOrigin = Configuration.GetValue<string>("IdSrv:PublicOrigin"); ;
options.Events.RaiseErrorEvents = true;
options.Events.RaiseInformationEvents = true;
options.Events.RaiseFailureEvents = true;
options.Events.RaiseSuccessEvents = true;
options.UserInteraction.LoginUrl = "/Account/Login";
options.UserInteraction.LogoutUrl = "/Account/Logout";
options.Authentication = new AuthenticationOptions()
{
CookieLifetime = TimeSpan.FromHours(10),
CookieSlidingExpiration = true
};
})
.AddConfigurationStore(options =>
{
options.ConfigureDbContext = b => b.UseSqlServer(connectionString, sql => sql.MigrationsAssembly(migrationsAssembly));
})
.AddOperationalStore(options =>
{ …Run Code Online (Sandbox Code Playgroud) c# dependency-injection .net-core asp.net-core identityserver4
有时,在服务注册期间,我需要从DI容器解析其他(已注册)服务。使用Autofac或DryIoc之类的容器,这没什么大不了的,因为您可以在一行上注册该服务,而在下一行上可以立即解决该问题。
但是,使用Microsoft的DI容器,您需要注册服务,然后构建服务提供程序,然后才可以从该IServiceProvider实例解析服务。
请参阅以下SO问题的可接受答案:ASP.NET核心模型绑定错误消息本地化
public void ConfigureServices(IServiceCollection services)
{
services.AddLocalization(options => { options.ResourcesPath = "Resources"; });
services.AddMvc(options =>
{
var F = services.BuildServiceProvider().GetService<IStringLocalizerFactory>();
var L = F.Create("ModelBindingMessages", "AspNetCoreLocalizationSample");
options.ModelBindingMessageProvider.ValueIsInvalidAccessor =
(x) => L["The value '{0}' is invalid."];
// omitted the rest of the snippet
})
}
Run Code Online (Sandbox Code Playgroud)
为了能够对ModelBindingMessageProvider.ValueIsInvalidAccessor消息进行本地化,答案建议IStringLocalizerFactory通过基于当前服务集合构建的服务提供商来解决。
那时“构建”服务提供者的成本是多少,并且这样做会有任何副作用,因为将至少再次构建一次服务提供者(在添加所有服务之后)?