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

时间:2015-08-09 17:27:19

标签: c# asp.net-core

我想访问我在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的实例以设置根变量。

2 个答案:

答案 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
}