user9326447
user9326447

Reputation: 99

IConfiguration object is null.

I'm trying to read connection strings from appsettings.json and I'm using:

services.AddSingleton(Configuration);

This line from startup throws null. I'm pretty new to core2.0. Can someone tell what I'm missing?

My startup:

public class Startup
{
    public static string ConnectionString { get; private set; }
    public IConfiguration Configuration { get; }
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.AddSingleton(Configuration);
        services.AddSingleton<IConfiguration>(Configuration);
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseMvc();
    }
}

My controller:

public class CreateController : Controller
{
    public IConfiguration _ConnectionString;
    public CreateController(IConfiguration configuration)
    {
        _ConnectionString = configuration;
    }

    public IEnumerable<string> Get()
    {
        Markets();
    }

    public string Markets()
    {
        using(SqlConnection con = new SqlConnection(_ConnectionString.GetSection("Data").GetSection("ConnectionString").Value))
        {
            return con.Database;
        }
    }
}

Upvotes: 3

Views: 9905

Answers (3)

Balah
Balah

Reputation: 2540

I've noticed your Startup is missing a constructor. In ASP.NET Core 2, when it calls startup (based on a typical WebHost.CreateDefaultBuilder(args).UseStartup<Startup>() inside a vanilla Program.BuildWebHost) will automatically pass the configuration into the Startup constructor:

public class Startup
{
    public IConfiguration Configuration { get; }

    // This configuration is automatic, if WebHost.CreateDefaultBuilder(args) is used in Program.cs
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

Just adding that will solve your IConfiguration is null issue.

Now, you should not have to add that Configuration into DI because with the defaults it should already be in there and you can add it as-is to your controller constructor. However, there's no harm in doing so.

Lastly, to join the chorus, using IConfiguration directly in you controllers is not a good idea. Rather look into strongly typed configuration settings. There are tutorials out there that can help - here's the first link I found - but the gist is your controller will end up looking sort of like this:

public class CreateController : Controller
{
    public ConnectionStrings _ConnectionStrings;
    public CreateController(IOptions<ConnectionStrings> connectionStrings)
    {
        _ConnectionStrings = connectionStrings.Value;
        ...

Upvotes: 5

Brad
Brad

Reputation: 4553

It is null because it hasn't been set. You need to build your configuration first which is best done in the constructor. As others have pointed out it is not recommended to do this.

Example

public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();

        if (env.IsDevelopment())
        {
            builder.AddUserSecrets<Startup>();
        }

        Configuration = builder.Build();
    }

    private IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton(Config);            
    }
}

Upvotes: 0

Marc LaFleur
Marc LaFleur

Reputation: 33114

You shouldn't be calling services.AddSingleton(Configuration) in ConfigureServices. It is already in the DI container by default.

You simply need to reference it within your Controler:

public class CreateController : Controller
{

    public IConfiguration _configuration;
    public CreateController(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public IEnumerable<string> Get()
    {
        Markets();
    }

    public string Markets()
    {
        var connectionString = _configuration.GetConnectionString("ConnectionStringName");
        using( SqlConnection con = new SqlConnection(connectionString) )
        {
            return con.Database;
        }

    }
}

Upvotes: 0

Related Questions