c# - WCF 定义多个具有不同 ServiceContract 类型的 ServiceContract

标签 c# wcf .net-4.0

我正在尝试编写两种完全不同类型的服务契约(Contract),这是一个应该支持多个客户端的服务契约(Contract)(IService)。

[ServiceContract(CallbackContract = typeof(IClientCallBack), SessionMode = SessionMode.Required)]
public interface IService
{
    [OperationContract]
    void GetSquaredAsync();
}

public interface IClientCallBack
{
    [OperationContract(IsOneWay = true)]
    void Result(int i);
}

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession, ConcurrencyMode = ConcurrencyMode.Multiple)]
class Service : IService
{
 void GetSquaredAsync(double x)
 {
   callback = OperationContext.Current.GetCallbackChannel<IClientCallBack>();
   callback.Result(x * x);
 }

这是另一个只允许 1 个客户端的情况:

[ServiceContract(SessionMode = SessionMode.Required)]
public interface ISuperUser
{
    [OperationContract]
    string WhoIsSpecial(string name);
}

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession, ConcurrencyMode = ConcurrencyMode.Single)]
public class SuperUser : ISuperUser
{
    public string WhoIsSpecial(string name)
    {
        return String.Format("{0} is special ^_^", name);
    }
}

这只是一个示例,因为我的实际 ServiceContracts 的实现太大了,无法在此处发布,但想法是相同的。我希望一个 ServiceContract 能够仅通过几个可用的函数调用来检查服务,而另一个 ServiceContract 使用回调并授予对由于同步问题而在任何给定时间我只希望 1 个客户端可以访问的函数的访问权限。我可以让一个服务主机同时支持这两个 ServiceContracts 吗?

最佳答案

好吧,我仍然无法为我的每项服务设置不同的并发模式,但我发现您可以将多个服务合约组合成一个,就像本例中的那样

class Service : IService, ISuperUser
{
    void GetSquaredAsync(double x)
    {
        callback = OperationContext.Current.GetCallbackChannel<IClientCallBack>();
        callback.Result(x * x);
    }

    public string WhoIsSpecial(string name)
    {
        return String.Format("{0} is special ^_^", name);
    }
}

然后我为每个接口(interface)启动一个具有不同端点的服务主机。

ServiceHost host = new ServiceHost(typeof(Service), httpUrl);

host.AddServiceEndpoint(typeof(IService), new NetTcpBinding(), IServiceUrl);
host.AddServiceEndpoint(typeof(ISuperUser), new NetTcpBinding(), ISuperUserUrl);

host.Open();

然后,我可以从客户端独立访问任一服务契约(Contract),具体取决于我想要使用哪个服务契约(Contract),而无需暴露另一个服务契约(Contract)的功能。这也允许我拥有一组使用回调的函数和另一组不使用回调的函数。希望这对其他人有帮助。

关于c# - WCF 定义多个具有不同 ServiceContract 类型的 ServiceContract,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18521916/

相关文章:

.NET 4 - Windows 窗体应用程序位置

c# - FormClosing属性有问题

performance - ConnectionManagement.MaxConnections和ServicePointManager.DefaultConnectionLimit有什么区别?

wcf - 一切都可以在 WCF 中以编程方式完成还是某些功能的配置文件?

c# - WCF 故障异常

c# - 是否可以在运行时根据 CPU 架构编写条件代码?

c# - 为什么这个特定的 TimeSpan 格式字符串在 .NET 4 中停止工作?

c# - 需要 C# 帮助来删除列表中的 obj

c# 从 var 中的第二个元素开始

c# - 如何根据日期自动运行 SQL 查询?