title: Configuration Validation in .NET
body: <p>I'm implementing a somewhat complex configuration section for a system monitoring project:</p>
  
  <pre><code>&lt;monitoring&gt;
    &lt;components&gt;
      &lt;component name="Remote Server"
                 statusProviderType="ClientEndpoint"
                 statusProviderName="endpoint1" /&gt;
    &lt;/components&gt;
  &lt;/montioring&gt;
  
  &lt;system.serviceModel&gt;
    &lt;client&gt;
      &lt;endpoint name="endpoint1"/&gt;
      &lt;!-- Config removed for brevity --&gt;
    &lt;/client&gt;
  &lt;/system.serviceModel&gt;
  </code></pre>
  
  <p>As in the example above, these configuration elements can refer to other configuration elements. In this case, a client endpoint which must implement a pre-determined contract which is part of the monitoring project.</p>
  
  <p>The built-in configuration handling deals with any obvious syntax errors and simple errors where values are outside of a valid range. The problem is where configuration is the source of more complex errors:</p>
  
  <ul>
  <li>Referencing an element which does not exist.</li>
  <li>Referencing a Type which does not meet certain conditions.</li>
  </ul>
  
  <p>Obviously, I wish to pick up on these errors, but where should this validation be done in the application?</p>
  
  <p>I've considered these options so far, but I'm not sure any of them is correct:</p>
  
  <ul>
  <li>The configuration element validates itself and throws exceptions when it is read. Keeps everything at a configuration level, but introduces problems when trying to "build" a configuration section to write it to a configuration file.</li>
  <li>The component which consumes the configuration validates the configuration values when they are passed to it and throws exceptions based on the information received. Allows for more flexibility with configuration elements, but makes it harder to identify where the problem's origin is.</li>
  <li>The component which consumes the configuration validates the configuration as it is needed by its operation and throws exceptions when configuration is invalid. This nicely separates the behaviour from the configuration, but makes it less obvious when the configuration is the source of the problem.</li>
  </ul>
  
  <p>Additionally, which exceptions are appropriate to throw for the sort of errors I am potentially handling? Bonus points for good reasoning with your answers.</p>
  
  <p>I'm feeling rather clueless with all the options available, but knowing how hard configuration can be to debug with some systems, I really want a sensible solution.</p>