是否真的需要.net core 2 API中的services.AddSingleton
我在.NET Core 2 Web API Controller中访问了appsettings.json,只需添加以下内容:
public class MyController : Controller { private readonly IConfiguration appConfig; public MyController(IConfiguration configuration) { appConfig = configuration; } }
在services.AddMvc();之后没有在Startup类ConfigureServices(IServiceCollection服务)中添加以下内容:
services.AddSingleton(Configuration);
我的方法有什么缺陷吗? 在.Net Core 2配置部分的官方文档中,没有提及使用’AddSingleton’甚至一次: https ://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration
也通过搜索我无法找到访问配置的相关内容! https://docs.microsoft.com/en-us/search/index?search=AddSingleton&scope=ASP.NET+Core
下面的链接显示AddSingleton,如同必须的步骤 :
访问控制器类中的appsettings.json值
https://blogs.technet.microsoft.com/dariuszporowski/tip-of-the-week-how-to-access-configuration-from-controller-in-asp-net-core-2-0/
正如ASP.NET Core 2.0的官方路线图所说:
默认情况下,在ASP.NET Core 2.0中,
IConfiguration
实例将添加到服务容器中,以便所有应用程序都可以通过容器轻松检索配置值
所以services.AddSingleton
(或类似的)已经被框架本身调用。
您可能会在WebHostBuilder.cs
文件中看到此行为,或者(在使用实用程序扩展方法时)在HostBuilder.cs
文件中看到此行为。