![](/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.