依赖注入不适用于 IConfiguration C#.Net Core

我使用以下代码注入了 IConfiguration:


 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>();

        }

}                             

在我的名为AppSettingUtil的类中使用它时,我在 IConfiguration 对象上遇到空指针异常。


下面是我正在使用的代码


public class AppSettingUtil

    {     

       public AppSettingUtil(IConfiguration configuration)

       {

          _configuration = configuration;

       }

       public IConfiguration Configuration { get; }

    }

在执行下面的函数时我得到空指针异常


 private static object GetDefault(string name)

    {

        if (_configuration[name] != null)

        {

            return Convert.ToInt32(_configuration[name]);

        }

        return null;

    }

执行此函数时对象_configuration为空,因此抛出空指针异常,


弑天下
浏览 259回答 2
2回答

SMILET

我在 ASP.Net Core 中使用这个并为我工作:public class Startup{&nbsp; &nbsp; public Startup(IHostingEnvironment env , IConfiguration configuration)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Configuration = configuration;&nbsp; &nbsp; }&nbsp; &nbsp; public IConfiguration Configuration { get; }&nbsp; &nbsp; public void ConfigureServices(IServiceCollection services)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; services.AddSingleton<IConfiguration>(provider => configuration);&nbsp; &nbsp; &nbsp; &nbsp; services.AddSingleton<AppSettingUtil>();&nbsp; &nbsp; }}

繁花如伊

也可以按如下方式进行:(我在 .net 核心控制台应用程序的主线程中执行此操作)public static void Main(string[] args)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; IConfigurationBuilder configurationBuilder = new ConfigurationBuilder();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Duplicate here any configuration sources you use.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; configurationBuilder.AddJsonFile("AppSettings.json");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; IConfiguration configuration = configurationBuilder.Build();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Program.token = configuration["token"];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Program.guidID = configuration["guidID"];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Program.kind = configuration["kind"];我在这个stackoverflow 问题中找到了解决方案。这个对我有用。希望它也对你有用。
打开App,查看更多内容
随时随地看视频慕课网APP