WatiN: The CurrentThread needs to have it's ApartmentState set to ApartmentState.STA to be able to automate Internet Explorer

Jonathan picture Jonathan · Dec 23, 2009 · Viewed 19.3k times · Source

I am calling WatiN from a C# windows service. When I invoke WatiN it throws the following exception. The CurrentThread needs to have it's ApartmentState set to ApartmentState.STA to be able to automate Internet Explorer

I have tried starting up a thread and setting the apartment state via

mythread.SetApartmentState(ApartmentState.STA)

but that resulted in another error

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.

I also tried adding an attribute to the Service entry point.

static class Program
{
      [STAThread]
      static void Main()
      {
          ...

Any ideas?

Answer

Pete Morgan picture Pete Morgan · Mar 17, 2011

I know Benjamin's already posted a 'working' answer, but I thought I'd add a couple of things I've experienced when I've got this error when trying to execute WatiN tests: For NUnit, you should add something like this to your app.config for the tests:

  <configSections>
    <sectionGroup name="NUnit">
      <section name="TestRunner" type="System.Configuration.NameValueSectionHandler"/>
    </sectionGroup>
  </configSections>
  <NUnit>
    <TestRunner>
      <!-- WatiN can only host IE in STA mode -->
      <add key="ApartmentState" value="STA"/>
    </TestRunner>
  </NUnit>

In MbUnit, modify your TestFixture attribute like this:

[TestFixture(ApartmentState = ApartmentState.STA)] 

HTH, Pete.

Ha - it's actually in the documentation. Doh! http://watin.org/documentation/sta-apartmentstate/