BadImageFormatException in 64-Bit Environment


[tweetmeme source=”jojitsoriano” only_single=false]

Scenario:

I have a WCF Service which instantiates a .Net DLL which in turn creates an instance of a COM object using System.Reflection. This WCF Service ran perfectly on a 32-bit Windows 7 machine and was even deployed successfully in a Windows XP 32-bit machine and other 32-bit machines by just copying the assembly and setting up IIS and other required permissions. When I tried to copy-deploy it in a 64-bit Windows 7 machine, I got this error that says the COM component is not registered. I am sure that the COM component is registered and running very well because it is a part of legacy application which is also running well.

image

I tried some suggestions from the web including using the Process Monitor tool from Sysinternals. Using the tool, I found that the code that created an instance of a COM object using System.Reflection looked for the registry entry from HKCR\CLSID but the 32-bit COM DLL was registered in HKCR\Wow6432Node\CLSID.

Naturally as a developer, I opened the source code for the WCF service in Visual Studio 2010 IDE. I was able to compile the source successfully with no error but when I launched the service url from the browser, I got this System.BadImageFormatException error:

image

This error is not only true for Wcf service but also to any .Net assemblies instantiating 32-bit components and COM components. See this blog for a good description of the scenario: http://blogs.msdn.com/joshwil/archive/2005/04/08/406567.aspx.

Here is the two-part solution:

1. Compile the .Net assemblies that instantiates the 32-bit components to target the x86 platform. By default, the projects are set to compile for Any CPU.

2. You will notice that the WCF service project cannot be set to target the x86 platform. This, according to Microsoft, is designed as such. The workaround is to set the “Enable 32-bit Applications” property in the Advanced Settings of the application pool to True.

image

I hope this will save you time when you encounter this error.

This work is licensed under a Creative Commons Attribution By license.
Advertisements
This entry was posted in .Net Tips, Silverlight and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s