Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using IConfiguration globally in mvc6

I have Probably been staring at this for to long, but I have jumped into MVC6 for asp.net for the last few days, while I am really enjoying this, I can't seem to find a convenient way to access the Configuration after it is defined in Start.cs with

Configuration = new Configuration()
    .AddJsonFile("config.json")
    ...

So, do I need to add it to the DI or is it already there? Or should I create a new instance whenever I need to use it, as it is possible to create different configurations (such as for IIdentityMessageService) create a sendgrid.json and load it within the Service itself?

There is probably a very easy solution, but like I said I have looking at this for days now.

like image 870
Craig Russell Avatar asked Nov 27 '14 22:11

Craig Russell


1 Answers

Only do the loading of Configurations in your Startup.cs. If you need them elsewhere later you could load the values into appropriate POCOs and register them in the DI so you can inject them where you need them. This allows you to organize your configuration in different files, and in different POCOs in a way that makes sense to your application. There is already built in support for this in the dependency injection. Here is how you would do it:

A POCO to put your configuration in:

public class SomeOptions
{
    public string EndpointUrl { get; set; }
}

Your Startup.cs loads the configuration into the POCO and registers it in the DI.

public class Startup
{
    public Startup()
    {
        Configuration = new Configuration()
                    .AddJsonFile("Config.json")
                    .AddEnvironmentVariables();
    }

    public IConfiguration Configuration { get; set; }

    public void Configure(IApplicationBuilder app)
    {
        app.UseMvc();
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<SomeOptions>(options => 
            options.EndpointUrl = Configuration.Get("EndpointUrl"));

        services.AddMvc();
    }
}

Then in your controller get the configuration POCO you created in the Startup.cs through dependency injection like this:

public class SomeController
{
    private string _endpointUrl;
    public SomeController(IOptions<SomeOptions> options)
    {
        _endpointUrl = options.Options.EndpointUrl;
    }
}

Tested with 1.0.0-beta1 builds of aspnet5.

For more information see The fundamentals of ASP.Net 5 Configuration.

like image 60
AndersNS Avatar answered Nov 06 '22 08:11

AndersNS