“ InvalidOperationException:没有注册类型'Microsoft.Extensions.Configuration.IConfiguration'的服务。”

时间:2018-10-26 20:11:58

标签: c# .net asp.net-core

我是编程的新手,还是c#和.NET Core的新手。

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

我正在尝试让应用程序读取“你好!”从appsettings.json中获取并显示在屏幕上。

这是我的Startup.cs

import { API } from './actions-beta'
import * as lib from './lib';   // import the module with B

describe('test A', () => {
  test('', () => {
    const fn = API()
    console.log(fn)
    const spy = jest.spyOn(lib, 'B')   // spy on B using its module
    fn.a()
    expect(spy).toHaveBeenCalled()   // SUCCESS
  })
})

这是我的Program.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);
            });
        }
    }
}

这是我的appsettings.json:

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();
        }
    }
}

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

由于无法解决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);
        });
    }
}