gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:33:02 25 4
gpt4 key购买 nike

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

[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 相同的服务实例调用 Second 函数。

最佳答案

你可以做两件事:

将 Second 移动到 IFirst 这样

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com