从.NET Core 2中的类读取appsettings.json

编程入门 行业动态 更新时间:2024-10-24 20:15:26
本文介绍了从.NET Core 2中的类读取appsettings.json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要从业务类的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

本文发布于:2023-11-02 15:01:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1552709.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Core   NET   json   appsettings

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!