ASPNet.Core从引用的程序集中读取appsettings?

时间:2017-10-26 21:26:39

标签: c# asp.net-core-mvc-2.0

我们正在构建一个ASPNet.Core微服务(HSMService),我们从另一个ASPNet.Core项目(HSM)引用了几个程序集。 HSM程序集需要读取HSMService根目录中的appsettings.json文件以设置一些值。

在HSM项目的单元测试中,appsettings.json文件位于测试项目的根目录中,我们正在使用 .SetPath(Directory.GetCurrentDirectory())阅读值。

当我们在HSMService中引用HSM程序集时,它无法正常工作,它正在尝试从DLL所在的/bin/Debug/netstandard2.0目录加载。

是否可以在HSM程序集中加载HSMService中的appsettings.json文件,还是应该将值的设置移动到HSMService的代码中?我会把它放在哪里?

1 个答案:

答案 0 :(得分:0)

我们决定修改程序集,使构造函数中的参数指向appsettings.json文件

public class HSMController : Controller
{
    private readonly IHostingEnvironment _hostingEnvironment;
    public string contentRootPath { get; set; }

    public HSMController(IHostingEnvironment hostingEnvironment)
    {
        _hostingEnvironment = hostingEnvironment;
        contentRootPath = _hostingEnvironment.ContentRootPath;
    }

    [Route("/PingHSM")]
    [HttpGet]
    [ProducesResponseType(typeof(ApiResponse), 200)]
    [ProducesResponseType(typeof(ApiResponse), 500)]
    public IActionResult PingHSM()
    {
        IHSM hsm = HSMFactory.GetInstance(contentRootPath);
        return Ok(hsm.PingHSM());
    }
}

HSMFactory中的构造函数负责获取contentRootPath并设置Config变量。

public static IHSM GetInstance(string configPath)
{
    // for now, there's only one
    Type t = GetImplements(typeof(IHSM)).FirstOrDefault();
    ConstructorInfo ctor = t.GetConstructor(new Type[] { typeof(string) });// assume empty constructor
    return ctor.Invoke(new object[] { configPath }) as IHSM;
}
相关问题