是services.AddSingleton< IConfiguration>。 NET Core 2 API真正需要的 [英] Is services.AddSingleton<IConfiguration> really needed in .net core 2 API

查看:428
本文介绍了是services.AddSingleton< IConfiguration>。 NET Core 2 API真正需要的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只需添加以下内容即可访问.NET Core 2 Web API Controller中的appsettings.json:

I accessed appsettings.json In .NET Core 2 Web API Controller simply by adding below:

public class MyController : Controller
    {
        private readonly IConfiguration appConfig;

        public MyController(IConfiguration configuration)
        {
            appConfig = configuration;
        }
    }

在启动类 ConfigureServices( IServiceCollection服务),位于services.AddMvc();之后:

Without adding below in Startup class ConfigureServices(IServiceCollection services) after services.AddMvc();:

services.AddSingleton<IConfiguration>(Configuration);

我的方法是否存在缺陷?在.Net Core 2配置的官方文档部分中,甚至没有一次不提及使用 AddSingleton: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration

Is there any flaws in my approach? In official docs for .Net Core 2 configuration section, its not mentioned to use 'AddSingleton' not even once: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration

也可以通过搜索I找不到与配置相关的内容!
https:// docs .microsoft.com / en-us / search / index?search = AddSingleton& scope = ASP.NET + Core

also by searching I couldn't find related content with accessing configuration! https://docs.microsoft.com/en-us/search/index?search=AddSingleton&scope=ASP.NET+Core

下面的链接显示了 AddSingleton就像强制步骤一样

访问控制器类中的appsettings.json值

https://blogs.technet.microsoft .com / dariuszporowski /本周技巧如何从asp-net-core-2-0 /

推荐答案

作为 ASP.NET Core 2.0的官方路线图说:


默认情况下,将在ASP.NET Core 2.0中将 IConfiguration 实例添加到服务容器中,因此所有应用程序都可以通过容器轻松地获取配置值

An IConfiguration instance will be added to the services container by default in ASP.NET Core 2.0, so that all applications can easily retrieve configuration values via the container

因此 services.AddSingleton< IConfiguration> (或类似名称)。

您可能会在 WebHostBuilder.cs 文件或(使用实用程序扩展方法时)在 HostBuilder.cs 文件。

You may see this behavior inside WebHostBuilder.cs file or (when using the utility extension methods) inside HostBuilder.cs file.

这篇关于是services.AddSingleton&lt; IConfiguration&gt;。 NET Core 2 API真正需要的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆