On ASP.NET Web Forms I used to have an utility static class, called WebConfigSettings
, where I had all the app settings read from my Web.config file (for example WebConfigSettings.DebugModeEnabled
).
Is it a bad practice on MVC? Shall I prefer using a non-static class and inject it on my controllers using dependency injection? If yes, where shall I put the property on the controller? I have read on this post that I should not use base controllers.

- 6,405
- 6
- 28
- 69

- 2,857
- 1
- 35
- 61
2 Answers
The problem with static classes is that you will be coupling your controllers with the .NET configuration system making them more difficult to unit test in isolation. You could have an IConfiguration
interface containing the necessary properties you will need throughout your application as well as an implementation of this interface reading the values of the properties from the config file. Now all that's left is to configure your favorite DI framework to inject the proper implementation of this interface into your controllers constructors. And in your unit tests you will be able to mock this interface.

- 1,023,142
- 271
- 3,287
- 2,928
-
That seems reasonable, but where am I going to put the actual instance of configuration class? On a base controller's property? – StockBreak Nov 04 '12 at 13:55
-
No, you could use constructor injection. Controllers that need this dependency will take `IConfiguration` as constructor argument. – Darin Dimitrov Nov 04 '12 at 13:56
-
Oh, thank you! Could you please point me to a good tutorial/guide about constructor injection with ASP.NET MVC controllers? – StockBreak Nov 04 '12 at 14:02
-
There are gazillions of tutorials out there. All you have to do is search. The specifics will of course depend on the actual dependency injection framework you are using. Here are some tutorials on the official ASP.NET MVC site: http://www.asp.net/mvc/overview/dependency-injection – Darin Dimitrov Nov 04 '12 at 14:05
-
Ok, thank you. I will adapt this to Ninject. Marked as answer anyway :) – StockBreak Nov 04 '12 at 14:06
This is the approach I use in MVC. I have a static AppSettings class with multiple properties - which is quite flexible as some are read from Web.config, the database/cache, or are even computed properties.
This could be used outside of the controller - possibly in the Model or the Views.

- 5,167
- 3
- 24
- 34
-
3Lol using a static class that is opening database connections and is used in views? really? that beaks every pattern out there including MVC – Stefan P. Nov 04 '12 at 12:54
-
Those properties are read from cache, but if the cache doesnt exist it is read from the database and placed in cache. DB is only read from on on app startup or if it is updated and the cache invalidated. – Judo Nov 04 '12 at 13:07