c# - WCF 一个服务实例多个 channel

标签 c# wcf servicehost

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

[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

在我的例子中,服务器创建了两个服务实例。我想要做的是为与 First 相同的 Service 实例调用 Second 函数。

最佳答案

你可以做两件事:

将第二个移至第一个,这样

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

    [OperationContract]
    void Second();
}

或者使用单例作为服务实例

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

关于c# - WCF 一个服务实例多个 channel ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8504059/

相关文章:

c# - 理解 MemoryMarshal.Cast 的返回值

wcf - wcf 服务中 ServiceHost 指令中的服务类型问题

.net - 为什么 WCF ServiceHost 一旦超出范围仍保持打开状态?

wcf - Azure Appfabric 缓存 + WCF Web 服务

c# - 将数据表从 C# 动态传递到 Javascript

c# - 异步 WCF 自托管服务

c# - 通过 nHibernate Criterion 使用 SQL CONVERT 函数

c# - WebHostBuilder.Build() MissingMethodException in .NET Core 迁移方案

c# - 添加通知图标后应用程序将不会在启动时启动

azure - 公开 WCF 服务并在 Azure 平台上仅使用一个 Web 角色在现有 ASP 应用程序上使用它