Search code examples
c#asp.net-core-mvc-2.0

ASPNet.Core reading appsettings from referenced assemblies?


We're building an ASPNet.Core microservice (HSMService) and we reference several assemblies from another ASPNet.Core project (HSM). The HSM assembly needs to read the appsettings.json file in the root of the HSMService to set some values.

In our unit tests of the HSM project, the appsettings.json file is located in the root of the test project and we are using .SetPath(Directory.GetCurrentDirectory()) to read the values.

It doesn't work when we reference the HSM assembly in the HSMService, it is trying to load from the /bin/Debug/netstandard2.0 directory where the DLL is located.

Is it possible to load the appsettings.json file from the HSMService in the HSM assembly or should we move the setting of the values into the code of the HSMService? Where would I put this?


Solution

  • We've decided to modify the Assembly to take a parameter in the constructor to point to the appsettings.json file

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

    The constructor in the HSMFactory takes care of taking the contentRootPath and setting the Config variables.

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