我想以测试驱动的方式开始在 C# 下使用 Remoting,但我卡住了。
我在该主题上发现的一件事是Marc Clifton 的这篇文章,但他似乎通过从控制台手动启动服务器来运行服务器。
我尝试在测试夹具中启动服务器(即注册服务类)。我可能也有接口的使用错误,但稍后会出现。
我总是收到频道已注册的异常(对于德语消息感到抱歉)。System.Runtime.Remoting.RemotingException:Der Channel tcp wurde bereits registriert。
在测试方法中注释掉 ChannelServices.RegisterChannell() 行之后,它发生在调用 Activator.GetObject() 中。
我试图将 StartServer() 放入一个线程中,但这也无济于事。我发现创建一个新的 AppDomain 可能是一种可能的方式,但还没有尝试过。
你能告诉我,如果我的方法本质上是错误的吗?我该如何解决?
using System;
using NUnit.Framework;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
namespace Bla.Tests.Remote
{
[TestFixture]
public class VerySimpleProxyTest
{
int port = 8082;
string proxyUri = "MyRemoteProxy";
string host = "localhost";
IChannel channel;
[SetUp]
public void SetUp()
{
StartServer();
}
[TearDown]
public void TearDown()
{
StopServer();
}
[Test]
public void UseRemoteService()
{
//IChannel clientChannel = new TcpClientChannel();
//ChannelServices.RegisterChannel(clientChannel, false);
string uri = String.Format("tcp://{0}:{1}/{2}", host, port, proxyUri);
IMyTestService remoteService = (IMyTestService)Activator.GetObject(typeof(IMyTestService), uri);
Assert.IsTrue(remoteService.Ping());
//ChannelServices.UnregisterChannel(clientChannel);
}
private void StartServer()
{
channel = new TcpServerChannel(port);
ChannelServices.RegisterChannel(channel, false);
RemotingConfiguration.RegisterWellKnownServiceType(typeof(MyTestService), proxyUri, WellKnownObjectMode.Singleton);
}
private void StopServer()
{
ChannelServices.UnregisterChannel(channel);
}
}
public interface IMyTestService
{
bool Ping();
}
public class MyTestService : MarshalByRefObject, IMyTestService
{
public bool Ping()
{
return true;
}
}
}