0

I've created a static class to use my configurations, but when I try to add the JSON file to the configuration I got an exception:

MyConfigurations.json:

{ "ConnectionString": "my connection string", ...}

My static class constructor:

static MyConfigurations() {
    var configuration = new Configuration()
        .AddJsonFile("MyConfigurations.json")
        .AddEnvironmentVariables();
    ...
    ...

My exception occurs when the .AddJsonFile is executed.

Exception: Object reference not set to an instance of an object."

StackTrace:

at Microsoft.Framework.ConfigurationModel.PathResolver.get_ApplicationBaseDirectory() at Microsoft.Framework.ConfigurationModel.JsonConfigurationExtension.AddJsonFile(IConfigurationSourceRoot configuration, String path, Boolean optional) at Microsoft.Framework.ConfigurationModel.JsonConfigurationExtension.AddJsonFile(IConfigurationSourceRoot configuration, String path) at Project.SharedKernel.MyConfigurations..cctor() in C:\Project\Project.SharedKernel\MyConfigurations.cs:line 86

mason
  • 31,774
  • 10
  • 77
  • 121
Cesar
  • 3,519
  • 2
  • 29
  • 43

1 Answers1

2

You have not set the application base path which the configuration API needs to determine where the physical config files live. You can set it using the SetBasePath extension method. A typical implementation looks like this:

public Startup(IApplicationEnvironment appEnv)
{
    var configuration = new ConfigurationBuilder()
        .SetBasePath(appEnv.ApplicationBasePath)
        .AddJsonFile("MyConfigurations.json")
        .AddEnvironmentVariables()
        .Build();
}

Note: this only counts for beta8, see this question. You don't have to specify the default base path anymore in RC1: https://github.com/aspnet/Announcements/issues/88.

Community
  • 1
  • 1
Henk Mollema
  • 44,194
  • 12
  • 93
  • 104
  • I'm trying to load this configuration in another project, in a class library with a static class to be shared with all projects of my solution, there is a way to work in this scenary? – Cesar Oct 26 '15 at 13:47
  • Just as a note: In RC1 the base bath is not longer needed: https://github.com/aspnet/Announcements/issues/88 – Juergen Gutsch Oct 26 '15 at 13:53
  • 1
    @Cesar I think your best option is to pass the `IApplicationEnvironment.ApplicationBasePath` to the static class. – Henk Mollema Oct 26 '15 at 13:57