0

我在一个程序集中有一堂课,我希望成为一个单身人士。我希望它由我的服务器应用程序创建,然后允许同一台机器上的另一个应用程序访问这个类实例。

我正在使用这个延迟加载实现来确保只存在一个实例:

Private Shared ReadOnly _instance As New Lazy(Of PersonX)(Function() New PersonX(), System.Threading.LazyThreadSafetyMode.ExecutionAndPublication)

Public Shared ReadOnly Property Instance() As PersonX
    Get
        Return _instance.Value
    End Get
End Property

然后我使用带有以下远程代码的Private Sub New:

Dim uri As String = String.Format("tcp://{0}:{1}/PersonX", "localhost", 1976)
RemotingServices.Marshal(Person.Instance, uri)
RemotingConfiguration.RegisterActivatedServiceType(GetType(PersonX))

在我的调用代码中,我创建了我的第一个实例:

Dim PersonX as SingletonTestClass.PersonX = SingletonTestClass.PersonX.Instance

我正在使用以下代码使用远程处理连接到实例:

Dim newPerson As SingletonTestClass.PersonX
Dim uri As String = String.Format("tcp://{0}:{1}/PersonX", "localhost", 1976)
newPerson = CType(Activator.GetObject(GetType(SingletonTestClass.PersonX), uri), SingletonTestClass.PersonX)

但是现在当我尝试访问对象属性时,我收到一条错误Requested Service not found on this line:

newPerson.Name = "Fred"
4

1 回答 1

0

要回答您的问题,您需要在编组 Remoting 对象之前注册一个频道:

请参阅简单、有效的 C# 示例:

public class Test : MarshalByRefObject
    {
        public string Echo(string message)
        {
            return "Echo: " + message;
        }
    }

private void button1_Click(object sender, EventArgs e)
        {
            ChannelServices.RegisterChannel(new TcpChannel(1234));
            Test test1 = new Test();
            RemotingServices.Marshal(test1, "TestService");

            Test test2 = (Test)Activator.GetObject(typeof(Test), "tcp://localhost:1234/TestService");
            MessageBox.Show(test2.Echo("Hey!"));
        }

确保防火墙没有阻止端口。

于 2012-11-22T15:46:37.307 回答