gpt4 book ai didi

c# - ASP.NET 5 - 在 Startup.Configure 中访问依赖容器

转载 作者:行者123 更新时间:2023-11-30 18:23:52 25 4
gpt4 key购买 nike

我想访问我的 Options 实例,它作为单例添加到 ConfigureServices 中。这是我的代码:

public class Startup
{
private IConfiguration Configuration { get; set; }

public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
var builder = new ConfigurationBuilder(appEnv.ApplicationBasePath)
.AddJsonFile("config.json")
.AddEnvironmentVariables();

Configuration = builder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton((serviceProvider) => ConfigurationBinder.Bind<Options>(Configuration));
}

public void Configure(IApplicationBuilder app)
{
var root = ""; // I want to access my Options instance to get root from it
var fileServerOptions = new FileServerOptions()
{
FileProvider = new PhysicalFileProvider(root)
};
app.UseFileServer(fileServerOptions);
}
}

我的问题是如何访问 Configure 方法中的 Options 实例来设置根变量。

最佳答案

How to use ConfigurationBinder in Configure method of startup.cs 中的建议,运行时可以将选项直接注入(inject)到 Configure 方法中:

public void Configure(IApplicationBuilder app, Options options)
{
// do something with options
}

关于c# - ASP.NET 5 - 在 Startup.Configure 中访问依赖容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31906898/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com