0
votes

I have custom sections in my project. The following line works for my Web API project from the web.config:

...
  <sectionGroup name="Project.Models">
    <section name="product" type="Project.Models.Configuration.ProductSettings" />
  </sectionGroup>
</configSections>  
<Project.Models>
   <product id="1" />    
</Project.Models>

When I run my unit tests, I get the following error:

System.Configuration.ConfigurationErrorsException : An error occurred creating the configuration section handler for Project.Models/product: Could not load type 'Project.Models.Configuration.ProductSettings' from assembly 'System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Could not load type 'Project.Models.Configuration.ProductSettings' from assembly 'System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.

Why do I have to specify the assembly name when referencing this from my unit tests app.config? This resolved the issue, but not sure why it's needed.

<section name="product" type="Project.Models.Configuration.ProductSettings, Project.Models" />
1

1 Answers

1
votes

It depends on the host that executes your code.

Without extra plumbing you'll find that in the inner workings of the Configuration namespace the type attribute is fed into the static method Type.GetType(string typeName).

For the typeName parameter you'll find in its description:

If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace.

The key part is currently executing assembly. That seems to be never the case for normal appdomains, and thus for the application that runs your unit-test (which I assume is VS).

The ASP.NET web hosting on the other hand provides an internal HttpConfigurationSystem class that re-implements the calls to GetSection. It is a little hard to follow but it looks like an internal class BuildManager loads all assemblies and iterate over all types, to find one that matches.

This explains the difference in behavior. It is adviced to always specifiy the assemblyname. In the asp.net scenario, if the assemblyname is present in the type parameter it short-circuits to the Type.GetType call which prevents the loading and inspection of all dll's in the bin folder of your webapp.