If you are using the HttpSelfHostConfiguration class that derives from HttpConfiguration, be careful when adding the Unity.WebAPI NuGet package to your project. The package adds a newer version of System.Web.Http.dll (where HttpConfiguration resides) which doesn’t play nice with System.Web.Http.SelfHost.dll (where HttpSelfHostConfiguration resides). Specifically, attempting to create an instance of the HttpSelfHostConfiguration class will fail with the following exception:
After a few hours of searching, I came across this MSDN article. The “Inheritance Rules” section of the article shows a matrix of compatible rules. I decompiled both versions of System.Web.Http.dll so I could see their respective assembly attributes. The one important difference I saw was the lack of the following attribute (or any security related attributes) for that matter in the newer System.Web.Http.dll which the NuGet package placed:
I believe the absence of this attribute (orSecurityTransparent or SecuritySafeCritical) means that the code in the new System.Web.Http assembly is “Critical.” Therefore, derived classes must also be treated as critical code. This not the case because of this attribute present in the System.Web.Http.SelfHost assembly:
According to the matrix, the error makes sense. However, what is not clear to me is the statement in “Assemblywide Annotation” section of the same MSDN article. It states that the following:
“Specifying no attribute causes the common language runtime to determine the transparency rules for you. All types and members are security-critical, except where being security-critical violates an inheritance rule.”
If we’re supposed to take the second sentence as meaning a derived class can be more restrictive than the base class, then the exception makes sense.
If you need to use Unity along with the HttpSelfHostConfiguration class, you are better off doing it without the NuGet package. It’s pretty easy so you’re not going to lose too much productivity or maintenance-wise.
For the specific scenario where I encountered this issue, please see this post.