WCF多渠道這是我的服務器應用程序的代碼:一個serivce例如
[ServiceContract]
public interface IFirst
{
[OperationContract]
void First();
}
[ServiceContract]
public interface ISecond
{
[OperationContract]
void Second();
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
class Service : IFirst, ISecond
{
static int count = 0;
int serviceID;
public Service()
{
serviceID = ++count;
Console.WriteLine("Service {0} created.", serviceID);
}
public void First()
{
Console.WriteLine("First function. ServiceID: {0}", serviceID);
}
public void Second()
{
Console.WriteLine("Second function. ServiceID: {0}", serviceID);
}
}
class Server
{
static void Main(string[] args)
{
ServiceHost host = new ServiceHost(typeof(Service), new Uri("net.tcp://localhost:8000"));
NetTcpBinding binding = new NetTcpBinding();
host.AddServiceEndpoint(typeof(IFirst), binding, "");
host.AddServiceEndpoint(typeof(ISecond), binding, "");
host.Open();
Console.WriteLine("Successfully opened port 8000.");
Console.ReadLine();
host.Close();
}
}
和客戶端:
class Client
{
static void Main(string[] args)
{
ChannelFactory<IFirst> firstFactory = new ChannelFactory<IFirst>(new NetTcpBinding(), new EndpointAddress("net.tcp://localhost:8000"));
IFirst iForst = firstFactory.CreateChannel();
iForst.First();
ChannelFactory<ISecond> secondFactory = new ChannelFactory<ISecond>(new NetTcpBinding(), new EndpointAddress("net.tcp://localhost:8000"));
ISecond iSecond = secondFactory.CreateChannel();
iSecond.Second();
Console.ReadLine();
}
}
當我運行它,我得到的輸出:
Successfully opened port 8000.
Service 1 created.
First function. ServiceID: 1
Service 2 created.
Second function. ServiceID: 2
在我的情況下,服務器創建兩個Service實例。我想要做的是調用第二個函數爲與第一次相同的服務實例。
+1 for InstanceContextMode.Single;) – 2011-12-20 09:18:56