0

I have a C# console app, and I'm defining an IConfiguration object as follows inside of Program.cs:

var myConfig = new ConfigurationBuilder()
            .AddJsonFile($"appsettings.{myEnvironment}.json", true, true)
            .Build();

... and I can reference settings from within that same Program.cs file like this:

var mySetting = myConfig.GetValue<string>("Section:SettingName");

However, I'm wondering what would be the way to access that same myConfig object from other files in my application? For instance, myConfig contains a connection string, but I don't actually make use of the connection string until a few layers deeper (inside of myService > myRepository > myDbContext). What is a best practice to read that connection string from inside of myRepository or myDbContext? Obviously, I can pass the connection string as a parameter from Program.cs and myService, but that seems inefficient.

WEFX
  • 8,298
  • 8
  • 66
  • 102

2 Answers2

2

You can use the build-in DI (Dependency Injection), which also works for .NET C# Console Applications as already mentioned here

How to use Dependency Injection in .Net core Console Application

ahybertz
  • 514
  • 4
  • 9
0

Pass IConfiguration to your constructor. You can use Bind calls to create objects from it, or just read it like a dictionary.

jjxtra
  • 20,415
  • 16
  • 100
  • 140