In my Startup.cs
class I have the following config build which initializes the db context:
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", true, true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json",true)
.AddEnvironmentVariables();
Configuration = builder.Build();
NHibernateUnitOfWork.Init(Configuration["ConnectionStrings:OracleConnection"]);
NHibernateUnitOfWork
is located in a different project as a class library project. I want to be able to inject (or somehow pass the settings) instead of using the NHibernateUnitOfWork.Init
in my Startup.cs
class.
I can build the appsettings in my class library but trying to avoid that.
What is a sane way to do this ?
You can inject it.
In your Startup.cs
class, you can add the following to your ConfigureServices(IServiceCollection services)
method:
services.AddSingleton(Configuration);
From there, you can use constructor injection and consume it downstream the same way you normally would:
public class SomeClass
{
public SomeClass(IConfigurationRoot configuration)
{
NHibernateUnitOfWork.Init(Configuration["ConnectionStrings:OracleConnection"]);
}
}
NOTE: This assumes Configuration
is defined in your Startup.cs
class:
public static IConfigurationRoot Configuration;
See this: Read appsettings json values in .NET Core Test Project
Essentially this is an integration solution using the TestServer. But if you're having to use the configuration, then it should probably be an integration test anyway.
The key to using the config in your main project inside your test project is the following:
"buildOptions": {
"copyToOutput": {
"include": [ "appsettings.Development.json" ]
}
}
which needs to go inside your main project's project.json
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.