作为WCF服务中的属性的服务

时间:2017-03-02 10:42:02

标签: c# .net wcf generics

我有一个用于在数据库上执行CRUD操作的通用服务,我希望将它作为WCF服务公开,如下所示:

[ServiceContract]
public interface ICrudService<T> where T : class
{
    [OperationContract]
    T Add(T arg);

    // Read ...
    // Update ...
    // Delete ...
}

不幸的是,WCF不支持泛型。

WCF Generic Class

WCF exposing generic type 'T'

所以我想创建一个WCF服务,将其他服务公开为属性。像这样:

[ServiceContract]
public interface IService1
{
    [OperationContract]
    FooService FooService { get; }

    [OperationContract]
    BarService BarService { get; }
}

public interface ICrudService<T> where T : class
{
    T Add(T arg);

    // Read ...
    // Update ...
    // Delete ...
}

public class FooService : ICrudService<Foo>
{
}

public class BarService : ICrudService<Bar>
{
}    

它不会让我将这些服务用作运营合同。还有其他方法可以达到这个目的吗?

1 个答案:

答案 0 :(得分:0)

这是真的:不幸的是WCF不支持泛型。但是有一种方法可以创建Dictionary<string, object>作为输入。我不确定那是你想要的,但我有同样的问题,我可以这样解决。

[Serializable]
public class WebServiceInputGetDataParams : ISerializable
{
    public Dictionary<string, object> Entries
    {
        get { return entries; }
    }


    private Dictionary<string, object> entries;
    public WebServiceInputGetDataParams()
    {
        entries = new Dictionary<string, object>();
    }
    protected WebServiceInputGetDataParams(SerializationInfo info, StreamingContext context)
    {
        entries = new Dictionary<string, object>();
        foreach (var entry in info)
        {
            entries.Add(entry.Name, entry.Value);
        }
    }
    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        foreach (var entry in entries)
        {
            info.AddValue(entry.Key, entry.Value);
        }
    }
}

它是一个输入类。你可以创建一个像这样的方法:

public void TestMethod(WebServiceInputGetDataParams input)
{
    //access the input through dictiobnary
    input.Entries
}