NUnit and STAThread

Heres an interesting one I ran into today:-

When you access OLE calls from .Net in .Net 2.0 or greater, you need to do it from an application where the main thread is set to Single Threaded Apartment (as opposed to Multile Threaded Apartment). What that means, i’m not entirely sure and didn’t spend the time to look in to i’m afraid.

This becomes an issue as the newer versions of NUnit are set to MTA by default – so when I updated an application from .Net 1.1 to .Net 2.0 and used the new NUnit, previously passing tests failed with the error – “System.Threading.ThreadStateException: Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it.”

There is a simple way around this, as I found on CodeCentric (http://codecentrix.blogspot.com/2007/12/nunit-and-stathread-story.html) – simply create an app.config file for the dll you are attempting to test, and add some NUnit appropriate settings to force NUnit to create the test environemnt as STA instead of MTA.

For convenience sake, here is the config file you would need (or add these sections to your existing config file):

<?xml version=”1.0″ encoding=”utf-8″?>
<configuration>
<configSections>
<sectionGroup name=”NUnit”>
<section name=”TestRunner” type=”System.Configuration.NameValueSectionHandler”/>
</sectionGroup>
</configSections>

<NUnit>
<TestRunner>
<add key=”ApartmentState” value=”STA” />
</TestRunner>
</NUnit>

</configuration>

Advertisements

3 thoughts on “NUnit and STAThread

  1. Hi Frater,

    “When you access OLE calls from .Net in .Net 2.0 or greater, you need to do it from an application where the main thread is set to Single Threaded Apartment (as opposed to Multile Threaded Apartment). What that means, i’m not entirely sure and didn’t spend the time to look in to i’m afraid.”

    To answer the above:

    In .net – COM interoperability, the main difference is in the apartment states. In .net, the default is MTA and if you make a call to a COM component without changing the apartment state to STA, the only way you can make it work is t do some custom marshalling and that is a tedious process.

    And in fact, it is the same in .Net 1.1. Why do you say it is in .net 2.0 onwards?

    Regards,

    Jv

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