繁体   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