3

I want to access my Options instance which is added as singleton in ConfigureServices. Here is my code:

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);
    }
}

My question is how to access instance of Options in Configure method to set root variable.

Henk Mollema
  • 44,194
  • 12
  • 93
  • 104
alisabzevari
  • 8,008
  • 6
  • 43
  • 67

2 Answers2

0

According to Joe Audette's comment this is the solution:

var options = app.ApplicationServices.GetService<Options>();
alisabzevari
  • 8,008
  • 6
  • 43
  • 67
0

As suggested in How to use ConfigurationBinder in Configure method of startup.cs, the runtime can inject the options directly into the Configure method:

public void Configure(IApplicationBuilder app, Options options)
{
    // do something with options
}
Community
  • 1
  • 1
Henk Mollema
  • 44,194
  • 12
  • 93
  • 104