I have a .NET 4.5 WCF service with async operations. I have integration tests which constructs the service host using NetNamedPipeBinding and hits the operation via a client.
However, each test like this always causes NUnit to report the following:
System.AppDomainUnloadedException: Attempted to access an unloaded AppDomain.
This can happen if the test(s) started a thread but did not stop it.
Make sure that all the threads started by the test(s) are stopped before completion.
Everything looks ok to me. Can anyone see what might be causing this? I have a complete code sample on GitHub: https://github.com/devlife/codesamples
I'm having the same problem. It looks as if the issue are "lenient" completion port threads (in the ThreadPool) that have been used by WCF to handle async IO.
When
ServiceHost.Close()
is used, it will signal all those threads that work is done, but they won't go away immediately, that is, they may outlive the end of theServiceHost.Close()
operation. Thus, the "shutdown" procedure races with the actual AppDomain unloading induced by NUnit due to the end of the test run.Basically, a simple
Thread.Sleep(<a couple of seconds>)
after aServiceHost.Close()
"fixes" this :-)After much searching around on the internet I couldn't find a robust solution for this issue (for a selection of similar issues, not all due to the same cause though, google "unit test appdomainunloadedexception"), short of having some way to suppress this warning itself.
I tried different bindings and transports (includind the NullTransport), but to no avail.
In the end I settled with this "solution":
The timeout of 3 seconds is totally arbitrary and so is the wait of 5ms between each retry. Sometimes I do get a "timeout", but most of the time it works.
I make sure that this code is called once for every test assembly (i.e. through a static ctor of a referenced type).
As usual in such cases YMMV.