我有一个简单的.NET远程客户端/服务器(下面的代码)…在控制台应用程序中托管/运行时,它可以正常工作,但在Windows服务中托管时,对Activator.GetObject返回的代理成员的所有调用都会导致NullReferenceException。
为了简化操作,我将所有这些内容放在一个控制台中,它工作得很好…创建了一个基本的Windows服务,并在onStart方法上放置了相同的代码,一旦我访问了“TheString”属性,就会得到一个NullReferenceException。
我可以确认没有其他异常,端口可用,服务以管理员身份运行。另外,我的解决方案需要一个单例,这就是我使用它的原因。
目前,这项工作正在Windows7上进行,这可能是一个因素。如果我能了解到更多的潜在错误可能是什么导致了这一点,我就能够搞清楚…我如何才能看到下面可能发生的事情(如水槽、格式化程序等)?
服务器代码:
var provider = new BinaryServerFormatterSinkProvider
{
TypeFilterLevel = TypeFilterLevel.Full
};
IDictionary properties = new Hashtable();
properties["port"] = 20001;
properties["exclusiveAddressUse"] = false;
_channel = new TcpChannel(properties, null, provider);
ChannelServices.RegisterChannel(_channel, false);
RemotingConfiguration.RegisterWellKnownServiceType(typeof(HostClass), "TheHost", WellKnownObjectMode.Singleton);
客户端代码:
var retInstance = (HostClass)Activator.GetObject(typeof(HostClass),
string.Format("tcp://{0}:{1}/TheHost", "MyHostName", 20001));
string host = retInstance.TheString; //This is where the NullReference is experienced
远程处理对象:
public class HostClass : MarshalByRefObject, IHostClass
{
public HostClass()
{
TheString = "Hello World";
}
public override object InitializeLifetimeService()
{
return null;
}
public string TheString { get; set; }
}
任何想法都会受到赞赏。