维护一个老软件,其中用到许多.net remoting技术,最近客户要求能够实现动态修改某个客户端激活的.net remoting的地址,为了尽可能避免修改代码,实现了一个新的泛型方法GetMarshalByRefObject<T>来代替New创建远程对象——如果你用了工厂模式,那么就很容易修改了,该方法实现如下:
public static T GetMarshalByRefObject<T>(string url) where T : MarshalByRefObject
{
System.Runtime.Remoting.Activation.UrlAttribute attribute = new System.Runtime.Remoting.Activation.UrlAttribute(url);
object[] activationAttributes = new object[] { attribute };
return (T)Activator.CreateInstance(typeof(T), null, activationAttributes);
}
其中T就是远程对象的类型,参数url是用户动态选择的地址。同时需要把客户端配置文件进行修改,移除相应的<activator/>。
注意采用客户端激活后就只能使用Activator.CreateInstance()而不能用Activator.GetObject()来创建远程对象了。
另如果需要测试某个.net remoting是否可用,可以使用如下的代码
try
{
tc = new TcpClient();
IPAddress IP = IPAddress;
int Port = port;
//test connecte status
tc.Connect(Ip, Port); // if not connected , will throw a error
tc.Close();
}
catch (Exception ee)
{
//……
}