0

我有一项服务需要将字符串泵送到一个帮助应用程序,该应用程序向用户显示来自服务的关键消息(Vista+ 不让服务访问 GUI)。由于我使用了基于 TCP 的 .NET Remoting,我想我会对 IPC 协议做同样的事情。但是,在获取对远程对象的引用后,在调用远程方法时出现以下异常:

MissingMethodException: No parameterless constructor defined for this object.

只需在类中添加一个无参数构造函数,就会在调用时给我一个 NullReferenceException。我做错了什么?我在下面包含了我的相关代码:

申请代码

public class MyMsgBus : MarshalByRefObject, IDisposable, IMxServeBus
{
    private Thread myThread = null;
    private volatile List<string> myMsgBus = null;
    private volatile bool myThreadAlive = false;
    private volatile bool myIsDisposed = false;
    private volatile bool myIsDisposing = false;
    private IpcChannel myIpc = null;

    public MyMsgBus(string busname)
    {
       myMsgBus = new List<string>();

       myIpc = CreateIpcChannel(busname);
       ChannelServices.RegisterChannel(myIpc);

       var entry = new WellKnownServiceTypeEntry(
          typeof(MxServeBus),
          "MyRemoteObj.rem",
          WellKnownObjectMode.Singleton);

       RemotingConfiguration.RegisterWellKnownServiceType(entry);
    }

    // defined in IMyMsgBus
    public void SendMessage(string message)
    {
       // do stuff
    }

    public static IpcChannel CreateIpcChannel(string portName)
    {
       var serverSinkProvider = new BinaryServerFormatterSinkProvider();
       serverSinkProvider.TypeFilterLevel = TypeFilterLevel.Low;

       IDictionary props = new Hashtable();
       props["portName"] = portName;
       props["authorizedGroup"] = "Authenticated Users";

       return new IpcChannel(props, null, serverSinkProvider);
    }

    public static IpcChannel CreateIpcChannelWithUniquePortName()
    {
       return CreateIpcChannel(Guid.NewGuid().ToString());
    }
}

测试客户端

static void Main(string[] args)
{
   var channel = MyMsgBus.CreateIpcChannelWithUniquePortName();
   ChannelServices.RegisterChannel(channel, true);

   var objUri = "ipc://MyMsgBus/MyRemoteObj.rem";
   IMyMsgBus lBus = (IMyMsgBus)Activator.GetObject(typeof(IMyMsgBus), objUri);
   lBus.SendMessage("test");
   Console.WriteLine();
}

在此先感谢您提供任何帮助。作为一个仅供参考,这是一个通过使用共享接口配置的远程处理实例,其中 IMyMsgBus 定义了应该可用于通过 IPC 调用的方法。

4

1 回答 1

0

您正在NullReferenceException添加无参数构造函数,因为正确初始化需要参数。如果不提供它,就会错过初始化的某些部分。

您应该重构代码以允许无参数构造函数为

   private bool _initialized = false;

    public MyMsgBus() {}

    public Initialize(string busname) // Make this part of interface    
    {
       myMsgBus = new List<string>();

       myIpc = CreateIpcChannel(busname);
       ChannelServices.RegisterChannel(myIpc);

       var entry = new WellKnownServiceTypeEntry(
          typeof(MxServeBus),
          "MyRemoteObj.rem",
          WellKnownObjectMode.Singleton);

       RemotingConfiguration.RegisterWellKnownServiceType(entry);
       _initialized = true;
    }

在所有其他公共方法中,检查_initialized标志以及throw NotInitializedException标志是否为假。

您应该将其用作

 IMyMsgBus lBus = (IMyMsgBus)Activator.GetObject(typeof(IMyMsgBus));
 lBus.Initialize(objUri);
 ... do Further operation
于 2013-01-10T15:23:47.163 回答