如何读取不在当前项目中的配置?

问题描述 投票:0回答:1

众所周知,对于基于.NET 6.0创建的WebAPI项目,Visual Studio会自动生成appsettings.json配置模板,可以通过构造函数注入读取当前项目(dll)中的配置。

那么如何读取不在当前项目中的配置呢?

c# .net visual-studio configuration
1个回答
0
投票

一个最小的例子:

我的项目:

班级图书馆:

public class MyConfiguration
    {
        private readonly string _mysection = "";

        public string MySection
        {
            get => _mysection;
        }
        public MyConfiguration()
        {
            var configurationBuilder = new ConfigurationBuilder();
            //notice the path here,I tried with Directory.GetCurrentDirectory() due to the class library was called by webapi projct which contains appsettings.json 
           //you would modify it for your requirement
            var path = Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json");
            configurationBuilder.AddJsonFile(path, false);
            var root = configurationBuilder.Build();
            _mysection = root.GetSection("MySection").Value;
            
        }
        

    }

在WebApi项目中创建该类的实例:

var mysection = new MyConfiguration().MySection;

我调试时效果很好:

© www.soinside.com 2019 - 2024. All rights reserved.