“InvalidOperationException:尚未注册类型‘Microsoft.Extensions.Configuration.IConfiguration’的服务。”

j. *_*iel 6 .net c# asp.net-core

我在某种程度上是编程新手,也是 C# 和 .NET Core 的新手。

我在尝试确定为什么这个简单的“hello world”应用程序因我的标题中的错误而失败时遇到了一些困难。

我试图让应用程序读取“Hello!!” 来自 appsettings.json 并将其显示在屏幕上。

这是我的 Startup.cs

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;

namespace My_NET_Core_Test_2
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, 
                                IHostingEnvironment env, 
                                ILoggerFactory loggerFactory,
                                IConfiguration configuration)
        {
            loggerFactory.AddConsole();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.Run(async (context) =>
            {
                var greeting = configuration["Greeting"];
                await context.Response.WriteAsync(greeting);
            });
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的 Program.cs:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;

namespace My_NET_Core_Test_2
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .UseApplicationInsights()
                .Build();

            host.Run();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的 appsettings.json:

{
  "Greeting":  "Hello!!",
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}
Run Code Online (Sandbox Code Playgroud)

我感谢您的帮助!

Mar*_*und 2

出现此问题的原因是无法解析 IConfiguration 实例。您可以通过ConfigurationBuilder在 Startup 构造函数中定义实例,它允许您定义从何处获取配置值。

下面是一个基本示例,其中 ConfigurationBuilder 将从内容根路径中的 appsettings.json 读取值并读取环境变量。

public class Startup
{
    private readonly IConfiguration _configuration;

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

    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, 
                            IHostingEnvironment env, 
                            ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.Run(async (context) =>
        {
            var greeting = _configuration["Greeting"];
            await context.Response.WriteAsync(greeting);
        });
    }
}
Run Code Online (Sandbox Code Playgroud)