NAL
NAL

Reputation: 74

Access configuration object (appsettings.json) in library project

I started a .net core web api project. I have one solution with the main project and many other project like DAL, Common etc.

I want to create a class in the Common project that will share configuration settings(appsettings.json) between my different library project. So, How can I acces Iconfiguration from that class ?

Is this a good way to do this ? Or should I create a class into the main project to get configuration data from other project ?

Upvotes: 1

Views: 1465

Answers (2)

LouraQ
LouraQ

Reputation: 6901

You can add the file as a link in yout project.

  1. Right click your project , then select "Add" ->"Existing Item..."
  2. Choose the file that you want to add to the solution
  3. Instead of hitting Enter or clicking the Add button, you need to click the down-arrow icon at the right edge of the Add button, and select "Add As Link".

Please refer to this link.

Upvotes: 0

tttdev
tttdev

Reputation: 48

One way to do it would be to create a Configuration Model based on your section/subsection from your appsettings.json file, add the configuration section in your Startup.cs class, then you can use the built-in dependency injection to inject the configuration anywhere you would need it.

For Example

appsettings.json :

{
  "MyConfiguration" : {
     "Configuration1" : "1",
   }
}

Your configuration model:

public class MyConfiguration 
{
   public int Configuration1 { get; set; }
}

Then in the StartupClass in the ConfigureServices method you have to add

services.Configure<MyConfiguration>(configuration.GetSection("MyConfiguration"));
services.AddOptions();

And when you want to use that Configuration somewhere in the code, you would just inject it in the constructor like so:

public class SomeClass 
{
  private MyConfiguration MyConfiguration { get; }

  public SomeClass(IOptions<MyConfiguration> myConfigurationOptions)
  {
    MyConfiguration = myConfigurationOptions.Value;
  }

//... more code
}

Then you can access it

MyConfiguration.Configuration1

Upvotes: 1

Related Questions