5

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 ?

John Laffoon
  • 2,885
  • 2
  • 26
  • 38
Cemre Mengü
  • 18,062
  • 27
  • 111
  • 169
  • See my answer here https://stackoverflow.com/questions/43080695/access-net-core-configuration-class-from-another-assembly – Razor Sep 30 '17 at 09:25

2 Answers2

5

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;
John Laffoon
  • 2,885
  • 2
  • 26
  • 38
0

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

Community
  • 1
  • 1
tonycdp
  • 137
  • 2
  • 9