我有一项服务需要将字符串泵送到帮助应用程序,该应用程序显示从服务到用户的关键消息(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();
}
提前感谢您提供任何帮助。作为FYI,这是通过使用共享接口配置的远程实例,其中IMyMsgBus定义了可通过IPC调用的方法。
答案 0 :(得分: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;
}
在所有其他公共方法中,如果flag为false,请检查_initialized
标志和throw NotInitializedException
。
您应该将其用作
IMyMsgBus lBus = (IMyMsgBus)Activator.GetObject(typeof(IMyMsgBus));
lBus.Initialize(objUri);
... do Further operation