ASP.. NET 5 -在Startup.Configure中访问依赖容器
本文关键字:访问 依赖 Configure Startup NET ASP | 更新日期: 2023-09-27 18:07:14
我想访问我的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
的实例来设置根变量
根据startup.cs的Configure方法中如何使用ConfigurationBinder的建议,运行时可以直接将选项注入Configure
方法:
public void Configure(IApplicationBuilder app, Options options)
{
// do something with options
}
根据Joe Audette的评论,这是解决方案:
var options = app.ApplicationServices.GetService<Options>();