netcore 非注入全局獲取配置文件

在netcore開發中,最多見的就是注入,好比想獲取appsettings.json的內容,咱們就須要去注入,而後在controller裏面去獲取,可是咱們若是想要在service中使用appsettings.json的內容,這樣就是一個問題,而且每一個controller去注入也是很是麻煩的事情html

 

下面的注入的(這種方法百度一下能夠出來幾百條相同的搜索結果。。。參見http://www.javashuo.com/article/p-dbyhkrdu-bg.htmljson

services.AddOptions();
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

而後獲取使用app

 

 

 

我想要在service類庫裏面使用,這時該如何使用哪?ide

直接上代碼:ui

    public class AppSettings
    {
        public string TestString { get; set; }
        public string ConfigVersion { get; set; }
        public string connectionString { get; set; }
        public string RedisExchangeHosts { get; set; }
        public string UploadPath { get; set; }
    }
        public Startup(IConfiguration configuration, ILoggerFactory factory, IHostingEnvironment env)
        {
            EnvironmentName = env.EnvironmentName;
            Configuration = configuration;
            // 將內置的日誌組件設置爲 NHibernate 的日誌組件
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)//增長環境配置文件,新建項目默認有
                .AddEnvironmentVariables();

            new AppSettingProvider().Initial(configuration);

            Configuration = builder.Build();

        }
    public class AppSettingProvider
    {
        private static AppSettings _myappSettings;
        public static AppSettings _appSettings { get { return _myappSettings; } }

        public void Initial(IConfiguration configuration)
        {
            _myappSettings =  new AppSettings() {
                ConfigVersion = configuration["AppSettings:ConfigVersion"],
                connectionString = configuration["AppSettings:connectionString"],
                TestString = configuration["AppSettings:TestString"],
                RedisExchangeHosts = configuration["AppSettings:RedisExchangeHosts"],
                UploadPath = configuration["AppSettings:UploadPath"]
            };
        }

    }

這樣,咱們在要使用的時候只須要AppSettingProvider._appSettings.xxxx便可,不須要進行重複的、實現idea

 

有錯誤或者片面地方歡迎指正spa

相關文章
相關標籤/搜索