【问题标题】:Generic Service Interface通用服务接口
【发布时间】:2011-06-03 16:19:03
【问题描述】:

我有一个通用服务接口:

[ServiceContract]
public interface IService<T> where T : Class1
{
    [OperationContract]
    void DoWork(T class1);
}

然后我有一个继承自它的具体服务:

public class Service : IService<Class1>
{
    public void DoWork(Class1 class1)
    {
    }
}

在我添加 webHttpEndpoint 以公开 JSON WS 之前,一切正常:

<service name="Service">
    <endpoint 
        address="" 
        binding="webHttpBinding" 
        behaviorConfiguration="webHttpBehavior"
        contract="IService"  />
</service>

<behavior name="webHttpBehavior">
    <enableWebScript />
</behavior>

事实上,我收到了这个错误:

合同名称“IService”不能 可以在合同列表中找到 由服务“Service”实现。

这是因为接口的通用定义。 有什么解决办法吗?

【问题讨论】:

  • 好吧,你的Service 没有实现IService(正如错误清楚地表明的那样) - 它实现了IService&lt;Class1&gt; - 这是一个不同的接口......
  • 感谢您的回答。如何在我的 web.config 中设置它?
  • 您可以尝试使用contract="IService&lt;Class1&gt;",但恐怕这行不通。 WCF 不太适合泛型.....
  • 感谢您的回答。它不起作用。

标签: wcf


【解决方案1】:

在我看来(并且基于您所说的),界面不需要是通用的。调用者只需要知道有一个 DoWork 操作即可。

所以基本上,将具体类更改为泛型而不是接口。

public class Service<T> : IService where T : Class1
{
    public void DoWork()
    {
    }
}

澄清问题后编辑:您还需要在配置文件中提供通用参数:

contract="YourAssembly.IService`1[[YourAssembly.Class1, YourAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]"

这里有一个类似的问题:Inheriting from a generic contract in WCF

【讨论】:

  • 感谢您的回答。编辑了问题:-)
  • 再次感谢。我的合同现在看起来像这样:contract="WebApplication1.IService`1[[WebApplication1.Class1, WebApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]" 但它不起作用。
【解决方案2】:

您必须将合约的类型名称正确写入配置。 IService不是IService&lt;Class1&gt;的名字!!!

配置应如下所示:

<service name="Service">
    <endpoint 
        address="" 
        binding="webHttpBinding" 
        behaviorConfiguration="webHttpBehavior"
        contract="IService`1[Class1]"  />
</service>

<behavior name="webHttpBehavior">
    <enableWebScript />
</behavior>

请注意,如果您的合同或服务位于任何命名空间中,则命名空间应包含在配置中。

或者如果需要全名:

<service name="Namespace.Service, AssemblyName">
    <endpoint 
        address="" 
        binding="webHttpBinding" 
        behaviorConfiguration="webHttpBehavior"
        contract="Namespace.IService`1[[Namespace.Class1, AssemblyName]], AssemblyName"  />
</service>

<behavior name="webHttpBehavior">
    <enableWebScript />
</behavior> 

【讨论】:

  • 感谢您的回答。同样的错误。可以举个真实的例子吗?
  • 完整的类型名称对我也不起作用,仍然 WCF 找不到合同。
【解决方案3】:

您的 Class1 在哪里.....不要指定任何特定的类,而是使用 class 将其作为引用类型

试试这个...

 [ServiceContract]public interface IService<T> where T : class
    { 
       [OperationContract] 
       void DoWork();
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-18
    • 2019-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-08
    • 2011-09-07
    相关资源
    最近更新 更多