通用服务合同

时间:2011-06-02 15:44:22

标签: wcf

我需要一个通用的服务合同,但如果我这样做,我会收到此错误:

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

在服务'z.t'实施的合同列表中找不到合同名称'x.y'。

3 个答案:

答案 0 :(得分:0)

只要您为界面使用封闭式通用设备,它就可以正常工作 - 请参阅下文。您不能做的是将开放式通用作为合同类型。

public class StackOverflow_6216858_751090
{
    public class MyClass { }
    [ServiceContract]
    public interface ITest<T> where T : MyClass
    {
        [OperationContract]
        string Echo(string text);
    }
    public class Service : ITest<MyClass>
    {
        public string Echo(string text)
        {
            return text;
        }
    }
    static Binding GetBinding()
    {
        BasicHttpBinding result = new BasicHttpBinding();
        //Change binding settings here
        return result;
    }
    public static void Test()
    {
        string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
        ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
        host.AddServiceEndpoint(typeof(ITest<MyClass>), GetBinding(), "");
        host.Open();
        Console.WriteLine("Host opened");

        ChannelFactory<ITest<MyClass>> factory = new ChannelFactory<ITest<MyClass>>(GetBinding(), new EndpointAddress(baseAddress));
        ITest<MyClass> proxy = factory.CreateChannel();
        Console.WriteLine(proxy.Echo("Hello"));

        ((IClientChannel)proxy).Close();
        factory.Close();

        Console.Write("Press ENTER to close the host");
        Console.ReadLine();
        host.Close();
    }
}

答案 1 :(得分:0)

您的服务合同无法互操作。不可能通过WSDL公开这样的泛型。

请查看本文(link)以获取可能的解决方法。

答案 2 :(得分:0)

如果您在客户端使用服务引用,则generic将失败。

在客户端使用以下通用:

var myBinding = new BasicHttpBinding();
var myEndpoint = new EndpointAddress("");
var myChannelFactory = new ChannelFactory<IService>(myBinding, myEndpoint);
IService gks = myChannelFactory.CreateChannel();