2017-03-02 250 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