![](/img/trans.png)
[英]How to read appsettings.json in any Class with .Net core 5
[英]Read appsettings.json from a class in .NET Core 2
我需要從業務類中的appsettings.json
文件(section: placeto
)中讀取屬性列表,但我無法訪問它們。 我需要將這些屬性公之於眾。
我在Program
類中添加了該文件:
這是我的appsettings.json
:
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"placeto": {
"login": "fsdfsdfsfddfdfdfdf",
"trankey": "sdfsdfsdfsdfsdf"
}
}
第一 :使用program.cs
的默認值,因為它已添加配置:
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
第二步 :通過創建Iconfiguration
字段為您的類創建一個接口並通過依賴注入傳遞配置:
private readonly IConfiguration Configuration;
然后通過構造函數傳遞它:
public Test(IConfiguration configuration)
{
Configuration = configuration;
}
然后為您的類創建一個接口,以便正確使用Dependency Injection
。 然后,可以創建它的實例,而無需將IConfiguration
傳遞給它。
這是類和接口:
using Microsoft.Extensions.Configuration;
namespace GetUserIdAsyncNullExample
{
public interface ITest { void Method(); }
public class Test : ITest
{
public Test(IConfiguration configuration)
{
Configuration = configuration;
}
private readonly IConfiguration Configuration;
public void Method()
{
string here = Configuration["placeto:login"];
}
}
}
第三 :然后在您的startup.cs中通過調用以下方法為您的類實現依賴注入:
services.AddSingleton< ITest, Test>();
在您的ConfigureServices
方法中
現在,您可以將類實例傳遞給Dependency Injection使用的任何類。
例如,如果您有ExampleController
其中使用您的類的ExampleController
,請執行以下操作:
private readonly ITest _test;
public ExampleController(ITest test)
{
_test = test;
}
現在你有_test實例可以在控制器的任何地方訪問它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.