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 ?

1

2 Answers 2

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;
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.