簡體   English   中英

靜態方法中的ASP.NET MVC訪問配置

[英]ASP.NET MVC access configuration in static methods

我正在使用asp.net核心,並且可以使用標准的DI機制將應用程序配置加載到控制器中,但現在我需要在靜態類的靜態方法中訪問該配置(在這種情況下,它是一堆輔助方法,需要一些配置設置)

到目前為止,我一直在將相關的設置條目作為參數傳遞,但是我想知道是否有更好的方法直接從DI服務集合存儲它的任何地方直接獲取整個config對象。

這個問題對我來說似乎很有趣,因為最近我一直在處理類似的問題,並且我采用三種不同的方法(非常歡迎評論,優點和缺點):

表1.A -第一個也是hacky ...如果您在其中添加擴展方法(我們稱其為UtilsProvider),然后在配置中獲得調用該estension方法的配置,該怎么辦?

 public static class UtilsProvider
    {
        private static string _configItemOne;

        public static IServiceProvider SetUtilsProviderConfiguration(this IServiceProvider serviceProvider, IConfigurationRoot configuration)
        {
            // just as an example:
            _configItemOne= configuration.GetValue<string>("CONFIGITEMONE");
            return serviceProvider;
        }
        // AND ALL YOUR UTILS THAT WOULD USE THAT CONFIG COULD USE IT
    }

並且,將從您的Startup類的Configure方法中調用該擴展方法:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider serviceProvider)
            {
                #region AddUtilsConfig

                serviceProvider.SetUtilsProviderConfiguration(Configuration);

                #endregion

...

1.B. -除了傳遞整個IConfigurationRoot實例之外,我們還可以將諸如具體參數或客戶端之類的許多信息傳遞給保存環境配置值的服務,並在您第一次需要configu屬性時從靜態類中調用該服務。

2.-這里也介紹了另一種可行的方法(下面的鏈接),但包含一些類似的方法,該方法是將HostingEnvironment傳遞給啟動類( http://www.blakepell.com)中相同的Configure方法中的一個靜態類。 / asp-net-core-dependency-injection和自定義類

public static class UtilsProvider
    {

        public static IHostingEnvironment HostingEnvironment { get; set; }        

...
    }

而在啟動...

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            ...

            // Have to be careful with static properties, they persist throughout the life time
            // of the application.  
            UtilsProvider.HostingEnvironment = env;
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM