Follow this process:
1.) What I have done is map a section of the AppSettings.json file to an object.
A.) Add the configuration settings to json
file.
"MyConfiguration": {
"DBServer": "MyDBServer",
"DBName": "MyDatabase"
}
B.) Create a class to use strongly typed configurations.
public class MyConfiguration
{
public string DBServer { get; set;}
public string DBName { get; set;}
}
C.) Map the JSON configurations to the MyConfiguration
object in the Startup
class.
public class Startup
{
//Make sure you add this.
public IConfigurationRoot Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
...
var configSection = Configuration.GetSection("MyConfiguration");
services.Configure<MyConfiguration>(configSection);
//Use one of the following.
Services.AddScoped<MyClass>();
Services.AddTransient<MyClass>();
Services.AddSingleton<MyClass>();
Services.AddInstance<MyClass>();
...
}
}
See this link for an explanation of the differences between
`AddSingleton()`
`AddScopped()`
`AddInstance()`
`AddTransient()`
2.) Change MyClass
to have MyConfiguration
object as a parameter of the MyClass
constructor.
//add this using statement and corresponding package
//"Microsoft.Extensions.Options.ConfigurationExtensions": "1.1.1"
using Microsoft.Extensions.Options;
public class MyClass
{
private MyConfiguration _configuration;
public MyClass(IOptions<MyConfiguration> configuration)
{
_configuraiton = configuraiton.Value;
}
}
3.) Add MyClass
as a parameter of the AnotherClass
constructor. Dependency Injection will create the MyClass
or reuse it depending on the scope of the object and how you setup that up in the Startup.ConfifureServices()
method.
public class AnotherClass
{
private MyClass _myclass;
public AnoherClass(MyClass myclass)
{
_myclass= myclass;
}
public SomeMethod()
{
//Use myClass here and you don't need to instantiate it.
_myclass
....
}
}