When to read configuration file parameters
Do you prefer reading parameters in a configuration file at one place and pass them as a parameter to modules/fun开发者_如何学Goctions or read them as and when required?
Yes, I strongly prefer passing them in as parameters and it's not close. The System.Configuration
classes should never never never pervade into your classes beyond setting up the application root.
- By passing them as parameters, you make dependencies explicit.
- You avoid having your domain classes be dependent on
System.Configuration
. - If you don't pass them in as parameters (but instead read them when/where needed), you are violating SRP.
- If you don't pass them in as parameters (but instead read them when/where needed), you make testing difficult.
- If you don't pass them in as parameters (but instead read them when/where needed), you have increased your maintenance costs.
I have to disagree with Jason's answer.
It's generally better for components to read their own configuration from the configuration file.
For example, in a classic 3-tier architecture (presentation, business logic and data access), it's better for the data access tier to get its own configuration (database connection strings, etc.) from the application configuration file, rather than the presentation tier needing to be concerned with it.
Other examples from the Framework:
The WCF infrastructure reads its own, complex, configuration information from the application configuration file. It would be ludicrous to expect an application that wants to use WCF to have to read this configuration information and pass it on.
The ASP.NET membership subsystem reads its own configuration data from
web.config
.
Pass them as parameters or make a class to read from them.. You should only read them from one place so if they change the refactor will be easy.
Depends on the scenario.
Usually a config file is related to configuration of the application; which means, based upon those configurations the application shall take decisions. For instance, the connection string parameter, or a parameter that tells the application to run under test-mode or live-mode.
Also, there could be a parameter that application needs only when a particular functionality is accessed.
It depends, do all the modules need these parameters? How often does your modules need them? Etc. One approach is to read them when the application start. The parameter objects are stored in a dependency injection container like Unity or Spring.NET. And the objects get injected when needed in my modules (when a new of the module is created).
If the parameters are rarely used, you can load it on demand when your modules are created.
精彩评论