从.NET Core 2中的类读取appsettings.json [英] Read appsettings.json from a class in .NET Core 2
问题描述
我需要从业务类的appsettings.json
文件(节:placeto
)中读取属性列表,但是我无法访问它们.我需要将这些属性公开.
I need to read a list of properties from appsettings.json
file (section: placeto
) in a business class, but I haven't been able to access them. I need these properties to be public.
我将文件添加到Program
类中:
这是我的appsettings.json
:
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"placeto": {
"login": "fsdfsdfsfddfdfdfdf",
"trankey": "sdfsdfsdfsdfsdf"
}
}
推荐答案
第一:使用program.cs
中的默认值,因为它已经添加了Configuration:
First : Use the default in program.cs
for it already adds Configuration:
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
字段来传递带有依赖项注入的配置:
Second : Create an Interface for your class and pass configuration with dependency injection by creating Iconfiguration
field:
private readonly IConfiguration Configuration;
然后将其传递给建设者:
then pass it by contructor:
public Test(IConfiguration configuration)
{
Configuration = configuration;
}
然后为您的课程创建一个接口,以正确使用Dependency Injection
.这样就可以创建它的实例,而无需将IConfiguration
传递给它.
Then create an interface for your class in order to use Dependency Injection
properly. Then one can create instances of it without needing to pass IConfiguration
to it.
这是类和接口:
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中,通过调用以下代码为您的类实现依赖注入:
Third: Then in your startup.cs implement Dependency Injection for your class by calling:
services.AddSingleton< ITest, Test>();
在您的ConfigureServices
方法中
现在,您也可以将类实例传递给Dependency Injection使用的任何类.
Now you can pass your class instances to any class used by Dependency Injection too.
例如,如果您要使用ExampleController
,请执行以下操作:
For example, if you have ExampleController
that you wanna use your class within do the following:
private readonly ITest _test;
public ExampleController(ITest test)
{
_test = test;
}
现在您有了_test实例,可以在控制器中的任何位置访问它.
And now you have _test instance to access it anywhere in your controller.
这篇关于从.NET Core 2中的类读取appsettings.json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!