ASP.NET MVC access configuration in static methods

Viewed 4981

I'm using asp.net core and loading application configuration into controllers using the standard DI mechanism fine, but I now need to access the configuration in a static method on a static class (its a bunch of helper methods that, in this case, require a few of the config settings)

So far I've been passing the relevant settings entries in as parameters but I wondered if there's a better way of simply getting the entire config object directly from wherever the DI services collection stores it.

1 Answers

This question seemed very interesting to me because I've been dealing with something similar recently and I have three different approaches (comments, pros and cons are very welcome):

1.a. - first one is hacky too... What if you add an extension method in that (let's call it UtilsProvider) and then you get the configuration calling that estension method in the

 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
    }

And, that extension method would be called from your Startup class Configure method:

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

                serviceProvider.SetUtilsProviderConfiguration(Configuration);

                #endregion

...

1.b. - Instead of passing the entire IConfigurationRoot instance we could pass many things like the concrete parameter or a client to a Service that holds environment configuration values and call that service from your static class first time you need that configu property.

2.- Another approach that should also work is described here (link below) but consist in something similar and it is to pass HostingEnvironment to a estatic class in the same Configure method in the startup class (http://www.blakepell.com/asp-net-core-dependency-injection-and-custom-classes )

public static class UtilsProvider
    {

        public static IHostingEnvironment HostingEnvironment { get; set; }        

...
    }

And in startup...

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;
        }
Related