2017-03-02 230 views
1

我有一个通用的服务在数据库上执行CRUD操作,我会非常想公开为这样一个WCF服务属性:服务在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> 
{ 
}  

它不会让我使用服务作为操作合同。有其他方法可以实现吗?

+0

这是我会严肃地质疑使用服务的价值。你为什么不能直接在数据库中调用你的数据库? –

+0

我想允许从客户端调用操作。我有要求使用UWP应用程序作为客户端。 –

回答

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 
} 
+0

你熟悉wcf概念吗?你想发布整个代码吗?它只是一个输入类。你应该自己写下剩下的部分。 – David

+0

对不起,我没有意识到受保护的方法是一个构造函数重载 –

+0

你绝对欢迎。它发生在我们所有人身上。不是吗? – David