New .Net Core 2 Site does not reconize Configuration.GetConnectionString

asp.net-core asp.net-core-2.0 asp.net-core-3.0 c# entity-framework-core

Question

I am creating a new web site from an empty ASP.NET Core 2 template and following the Microsoft Entity Framework Tutorial to help me get setup. At one point it has you add the code:

services.AddDbContext<SchoolContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

To the ConfigureServices() method of Startup.cs. I did this but in my project Visual Studio give me that little red line under Configuration in the Configuraiton.GetConnectionString

I had thought I was missing a using statement or even a package but the Visual Studio 2017 quick actions don't identify a using statement to use and I do have the Microsoft.AspNetCore.All package installed so I should have all the packages.

What am I missing that is making the Configuration not recognized?

Edit: The error is:

The name 'Configuration' does not exist in the current context

public void ConfigureServices(IServiceCollection services)
{
     services.AddDbContext<CollectionContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
     services.AddMvc();
}
1
14
8/24/2019 5:41:55 AM

Accepted Answer

You need to get the IConfiguration object via DI.
Add a IConfiguration argument to your Startup's constructor, and assign it to a Configuration property:

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }

I'm surprised how you don't have it though, because it's part of the template.

34
12/7/2017 7:51:55 PM

Popular Answer

1# install the NuGet package: Microsoft.Extensions.Configuration
2# add: using Microsoft.Extensions.Configuration;
3# Note that i have added this line in the code: public IConfiguration Configuration { get; }

 public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers(); 
            });
        }
    }


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow