卸载 AppDomain:
干净地重新启动 ServiceStack 主机的唯一方法是卸载它正在运行的应用程序域并在新的应用程序域中启动一个新实例。
您的问题与此问题和答案有关。
1:创建您的 AppHost(正常):
注册使用 IoC 容器AppHost
调用的对象的示例。MyTest
public class AppHost : AppSelfHostBase
{
public AppHost(): base("My ServiceStack Service", typeof(AppHost).Assembly)
{
}
public override void Configure(Funq.Container container)
{
container.Register<MyTest>(c => new MyTest());
}
}
public class MyTest
{
public string Name { get { return "Hello"; } }
}
2:创建一个IsolatedAppHost
类:
该类IsolatedAppHost
用于启动您的应用程序主机,它将在隔离的 AppDomain 中运行。您可以在此处启动和配置AppHost
您需要的任何内容,例如您的HttpTestableAppHost
.
public class IsolatedAppHost : MarshalByRefObject
{
readonly AppHost Host;
public IsolatedAppHost()
{
// Start your HttpTestableAppHost here
Host = new AppHost();
Host.Init();
Host.Start("http://*:8090/");
Console.WriteLine("ServiceStack is running in AppDomain '{0}'", AppDomain.CurrentDomain.FriendlyName);
}
public void RunTest(Action<AppHost> test)
{
test.Invoke(Host);
}
public void Teardown()
{
if(Host != null)
{
Console.WriteLine("Shutting down ServiceStack host");
if(Host.HasStarted)
Host.Stop();
Host.Dispose();
}
}
}
3:创建你的TestFixture
:
您的TestFixureSetup
方法将需要IsolatedAppHost
在新的AppDomain
. 并且TestFixtureTearDown
将确保AppHost
正确关闭和域。
[TestFixture]
public class Test
{
AppDomain ServiceStackAppDomain;
IsolatedAppHost IsolatedAppHost;
[TestFixtureSetUp]
public void TestFixtureSetup()
{
// Get the assembly of our host
var assemblyName = typeof(IsolatedAppHost).Assembly.GetName();
// Create new AppDomain
ServiceStackAppDomain = AppDomain.CreateDomain("ServiceStackAppDomain");
// Load our assembly
ServiceStackAppDomain.Load(assemblyName);
// Create instance
var handle = ServiceStackAppDomain.CreateInstance(assemblyName.FullName, "MyApp.Tests.IsolatedAppHost");
// Unwrap so we can access methods
IsolatedAppHost = (IsolatedAppHost)handle.Unwrap();
}
[TestFixtureTearDown]
public void TestFixtureTearDown()
{
// Tell ServiceStack to stop the host
IsolatedAppHost.Teardown();
// Shutdown the ServiceStack application
AppDomain.Unload(ServiceStackAppDomain);
ServiceStackAppDomain = null;
}
// Tests go here
}
4:运行测试:
由于测试运行器AppDomain
和AppHost
AppDomain
现在不同,我们不能AppHost
直接从我们的测试中访问。所以我们将测试传递RunTest
给IsolatedAppHost
.
IsolatedAppHost.RunTest(appHost => {
// Your test goes here
});
例如:
[Test]
public void TestWillPass()
{
IsolatedAppHost.RunTest(appHost => {
var t = appHost.TryResolve<MyTest>();
Assert.That(t.Name, Is.EqualTo("Hello"));
});
}
[Test]
public void TestWillFail()
{
IsolatedAppHost.RunTest(appHost => {
var t = appHost.TryResolve<MyTest>();
Assert.That(t.Name, Is.EqualTo("World"));
});
}
完整的源代码在这里。我希望这会有所帮助。