是 services.AddSingleton<IConfiguration>.net core 2 API 中确实需要 [英] Is services.AddSingleton<IConfiguration> really needed in .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;
}
}
在services.AddMvc();之后没有在Startup类中添加ConfigureServices(IServiceCollection services):
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
也通过搜索我找不到与访问配置相关的内容!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 好像是强制性步骤:
推荐答案
作为 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
(或类似的)已经被框架本身调用了.
So services.AddSingleton<IConfiguration>
(or similar) is already called by the framework itself.
您可能会在 中看到这种行为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<IConfiguration>.net core 2 API 中确实需要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!