Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
314 views
in Technique[技术] by (71.8m points)

c# - Read appsettings.json from a class in .NET Core 2

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.

I add the file in the Program class:

Class program

This is my appsettings.json:

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "placeto": {
    "login": "fsdfsdfsfddfdfdfdf",
    "trankey": "sdfsdfsdfsdfsdf"
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
}

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;
}

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.

Here is the class and Interface:

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"];
        }
    }
}

Third: Then in your startup.cs implement Dependency Injection for your class by calling:

services.AddSingleton< ITest, Test>();

in your ConfigureServices method

Now you can pass your class instances to any class used by Dependency Injection too.


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;          
 } 

And now you have _test instance to access it anywhere in your controller.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...