【发布时间】:2011-12-14 02:01:35
【问题描述】:
我是 WCF 新手,仍在尝试。
我有两个这样的 ServiceContract:
[ServiceContract]
public interface IFirst
{
[OperationContract(IsOneWay = true)]
void First();
}
[ServiceContract]
public interface ISecond
{
[OperationContract(IsOneWay = true)]
void Second();
}
在服务器端客户端类实现这些接口:
public class Client : IFirst, ISecond
{
static int count = 0;
int id;
public Client()
{
count++;
id = count;
Console.WriteLine("{0} client created.", id);
}
public void First()
{
Console.WriteLine("First from: " + id.ToString());
}
public void Second()
{
Console.WriteLine("Second: " + id.ToString());
}
}
和主持人:
ServiceHost host = new ServiceHost(typeof(Client), new Uri("net.tcp://localhost:8000"));
NetTcpBinding binding = new NetTcpBinding();
host.AddServiceEndpoint(typeof(IFirst), binding, "");
host.AddServiceEndpoint(typeof(ISecond), binding, "");
host.Open();
在客户端:
ChannelFactory<IFirst> firstFactory = new ChannelFactory<IFirst>(new NetTcpBinding(), new EndpointAddress("net.tcp://localhost:8000"));
IFirst iFirst = firstFactory.CreateChannel();
iFirst.First();
ChannelFactory<ISecond> secondFactory = new ChannelFactory<ISecond>(new NetTcpBinding(), new EndpointAddress("net.tcp://localhost:8000"));
ISecond iSecond = secondFactory.CreateChannel();
iSecond.First();
这很好用。它调用 First 和 Second 方法,但每次调用都会创建 Client 类的新实例。很明显,因为当客户端创建通道时,服务会创建客户端对象的新实例。我希望实现的是在 First 之后调用 Second,但对于 Client 的同一实例。甚至可能吗?我知道我可以将这两种方法放在一项服务中,但这不是我想要的。
【问题讨论】: