Reputation: 74
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
Reputation: 6901
You can add the file as a link
in yout project.
"Add" ->"Existing Item..."
Add As Link
".Please refer to this link.
Upvotes: 0
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