我想访问我在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);
}
}
我的问题是如何在Options
方法中访问Configure
的实例以设置根变量。
答案 0 :(得分:0)
根据Joe Audette的评论,这是解决方案:
var options = app.ApplicationServices.GetService<Options>();
答案 1 :(得分:0)
正如How to use ConfigurationBinder in Configure method of startup.cs中所建议的,运行时可以将选项直接注入Configure
方法:
public void Configure(IApplicationBuilder app, Options options)
{
// do something with options
}