Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency Injection not working for IConfiguration C#.Net Core

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,

like image 657
SwapnilKumbhar Avatar asked Dec 03 '22 10:12

SwapnilKumbhar


2 Answers

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>();
    }
}
like image 142
hassan.ef Avatar answered Dec 21 '22 12:12

hassan.ef


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.

like image 25
Ricardo Araújo Avatar answered Dec 21 '22 13:12

Ricardo Araújo