I have injected IConfiguration using following code:
public class InjectorConfig
{
/// <summary>
/// configuration for DI
/// </summary>
/// <param name="services"></param>
/// <param name="configuration"></param>
public static void Init(IServiceCollection services, IConfiguration configuration)
{
services.AddSingleton<IConfiguration>(provider => configuration);
services.AddSingleton<AppSettingUtil>();
}
}
while using this in my class called AppSettingUtil I am getting null pointer exception on IConfiguration object.
Below is the code I am using
public class AppSettingUtil
{
public AppSettingUtil(IConfiguration configuration)
{
_configuration = configuration;
}
public IConfiguration Configuration { get; }
}
While executing below function I am getting null pointer exception
private static object GetDefault(string name)
{
if (_configuration[name] != null)
{
return Convert.ToInt32(_configuration[name]);
}
return null;
}
While executing this function the object _configuration is null, and hence throwing null pointer exception,
I use this one in ASP.Net Core and works it for me:
public class Startup
{
public Startup(IHostingEnvironment env , IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IConfiguration>(provider => configuration);
services.AddSingleton<AppSettingUtil>();
}
}
It also can be done as follows:
(I did this in the main thread of a .net core console app)
public static void Main(string[] args)
{
IConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
// Duplicate here any configuration sources you use.
configurationBuilder.AddJsonFile("AppSettings.json");
IConfiguration configuration = configurationBuilder.Build();
Program.token = configuration["token"];
Program.guidID = configuration["guidID"];
Program.kind = configuration["kind"];
I found the solution in this stackoverflow question.
It works for me. Hope it works for you too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With