本文介绍了WCF一个服务实例的多个通道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的服务器应用程序代码:

This is my code for server application:

[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();

    }
}

当我运行它时,我得到输出:

When I run it I get output:

Successfully opened port 8000.
Service 1 created.
First function. ServiceID: 1
Service 2 created.
Second function. ServiceID: 2

在我的情况下,服务器创建两个Service实例.我想做的就是调用与First相同的Service实例的Second函数.

In my case server creates two instances of Service. What I want to do is call Second function for the same Service instance that First did.

推荐答案

您可以做两件事:

将第二名移至IFirst

Move Second to IFirst so

public interface IFirst
{
    [OperationContract]
    void First();

    [OperationContract]
    void Second();
}

或将Singleton用于服务实例

Or use a Singleton for the service instance

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
class Service : IFirst, ISecond
{
...
}

这篇关于WCF一个服务实例的多个通道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 19:37