Reputation: 675
I am creating an object from an object created in my appsetting.json, I add it through singleton but then I don't know how to access those values.
My class:
public class UserConfiguration
{
public string Username { get; set; }
public string Password { get; set; }
public string SecretKey{ get; set; }
}
In my startup.cs
var userCfg = Configuration.GetSection("UserConfig").Get<UserConfiguration>(); //.> success i've values
services.AddSingleton(userCfg);
services.AddControllers();
and i want use this class and I call this class from my controller api.
public class UserService : BaseService
{
public UserService(IConfiguration config): base(configuration)
{
}
public string GetData()
{
var userConfg = new UserConfiguration();
var key = user.SecretKey; //--> null but a instance is empty
return "ok"
}
}
but I don't know how to rescue the values of the singleton that I loaded in the Startup.cs
Upvotes: 0
Views: 2676
Reputation: 2388
Since you're registering UserConfiguration as Singleton with DI container, you can inject this object UserService constructor:
public class UserService : BaseService
{
private UserConfiguration _userConfiguration;
public UserService(IConfiguration config, UserConfiguration userConfiguration): base(configuration)
{
_userConfiguration = userConfiguration; //Injected in constructor by DI container
}
public string GetData()
{
var key = _userConfiguration .SecretKey;
return "ok"
}
}
However recommended approach to pass application configuration information to services is by using the Options pattern
services.Configure<UserConfiguration>(Configuration.GetSection("UserConfig"));
services.AddControllers();
Add then access the configuration option:
public class UserService : BaseService
{
private UserConfiguration _userConfiguration;
public UserService(IConfiguration config, IOptions<UserConfiguration> userConfiguration): base(configuration)
{
_userConfiguration = userConfiguration.Value; //Injected in constructor by DI container
}
public string GetData()
{
var key = _userConfiguration .SecretKey;
return "ok"
}
}
Upvotes: 1