asp.netcompilationdynamic-assemblies

.NET component behaviour difference when changing compilation configuration


I'm having problems with a piece of code that behaves differently depending on whether it was compiled in the Release or Debug configuration in Visual Studio. I have manually altered all the project compilation settings I can see on the Release config so that it matches the Debug one, but the problem persists.

The code (below) returns the Guid of the executing assembly:

private static Guid GetApplicationUid() 
{ 
   Assembly assembly = Assembly.GetCallingAssembly(); 
   GuidAttribute attribute = (GuidAttribute)assembly.GetCustomAttributes(typeof(GuidAttribute), false)[0]; 
   return new Guid(attribute.Value); 
}

The method fails with an "Index was outside the bounds of the array." exception when executed after compilation in Release mode. It works correctly in Debug mode. The reason this is that in this configuration, the assembly reference created by GetExecutingAssembly() is to a temporary assembly (eg. App_Web_eelfd0ff, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null) rather than the underlying "real" one.

Strangely enough, I have another component running in the same web that uses the same code and behaves the same regardless of the compilation mode.

Why is this happening and how to prevent it?


Solution

  • It's possible that when optimizations are enabled, the function is being inlined into a different assembly. Try adding MethodImplOptions.NoInlining, as per this answer so that the method is in the assembly you think it is.