我们使用 WCF 在客户端和服务器应用程序之间进行通信。客户端应用程序有许多功能需要与服务器通信 - 我们选择在多个类中实现它(职责分离)
目前,我们正在为每个对象创建新的 WCF 端点和服务契约 - 发票、会计、内容管理等。这会导致客户端和服务器上的大量端点配置(在移动到测试和生产平台)。
我想知道我是否可以定义一个可以提供多个服务联系实现的 WCF 端点。然后我们的配置文件将包含一个端点(到服务工厂),我可以通过指定我感兴趣的服务接口(interface)来请求不同的服务。
例如
using (IServiceClientFactory serviceClientFactory = new RealProxyServiceClientFactory())
{
// This is normal WCF proxy object creation.
IServiceFactory serviceFactory = serviceClientFactory.CreateInstance<IServiceFactory>("");
// This is what we would like to do
IInvoiceService invoiceService = serviceFactory.getService(typeof(IInvoiceService));
invoiceService.executeOperation(data);
}
线索是每个客户端/服务器对的单个端点配置,而不是我想提供的每个服务联系人的端点配置。
这可能吗?
最佳答案
我不是 100% 清楚你想做什么,但如果你只是想在同一个地址上托管不同的契约(Contract),并在一个服务类中实现,这是完全可能的。要共享端点地址,您必须确保为每个服务端点使用相同的绑定(bind)实例。
这是一个完整的示例,它定义了 3 个契约、1 个实现所有契约的服务类,以及一个在完全相同的地址具有 3 个契约端点的 ServiceHost:
using System;
using System.ServiceModel;
[ServiceContract]
interface IContractA
{
[OperationContract]
void A();
}
[ServiceContract]
interface IContractB
{
[OperationContract]
void B();
}
[ServiceContract]
interface IContractC
{
[OperationContract]
void C();
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
class Service : IContractA, IContractB, IContractC
{
public Service()
{
}
public void A()
{
Console.WriteLine("A");
}
public void B()
{
Console.WriteLine("B");
}
public void C()
{
Console.WriteLine("C");
}
}
class Program
{
public static void Main(string[] args)
{
Uri address = new Uri("net.pipe://localhost/Service/");
ServiceHost host = new ServiceHost(new Service(), address);
NetNamedPipeBinding binding = new NetNamedPipeBinding();
host.AddServiceEndpoint(typeof(IContractA), binding, string.Empty);
host.AddServiceEndpoint(typeof(IContractB), binding, string.Empty);
host.AddServiceEndpoint(typeof(IContractC), binding, string.Empty);
host.Open();
IContractA proxyA = ChannelFactory<IContractA>.CreateChannel(new NetNamedPipeBinding(), new EndpointAddress(address));
proxyA.A();
((IClientChannel)proxyA).Close();
IContractB proxyB = ChannelFactory<IContractB>.CreateChannel(new NetNamedPipeBinding(), new EndpointAddress(address));
proxyB.B();
((IClientChannel)proxyB).Close();
IContractC proxyC = ChannelFactory<IContractC>.CreateChannel(new NetNamedPipeBinding(), new EndpointAddress(address));
proxyC.C();
((IClientChannel)proxyC).Close();
host.Close();
}
}
关于c# - WCF 服务返回另一个服务(服务工厂?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1437411/