2012-04-01 45 views
1

我剛剛開始使用.NET MVC實驗4.如何使用WCF與MVC

是我有一個WCF服務,對於一些應用程序提供的數據,並想用它來使用MVC網站的事情以及。

我完全不熟悉這個,所以我想知道哪裏最好的地方連接到WCF是。我想WCF可以被認爲是模型,在這種情況下,最好的方法是將它放在控制器中。

但是,這是否真的正確或應該在模型層中使用服務?

+0

如果你是新來的MVC/WFC你可能要檢討http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-你先網上API – RickAndMSFT 2012-04-02 06:58:11

回答

2

我傾向於建築師這種使用存儲庫模式中,倉庫方法的返回情況下我的模型類:

在我的控制,我會簡單地初始化我的存儲庫的引用,並調用相應的方法。該倉庫將包裝WCF服務代理,並調用各種資源庫的方法從CustomerController

EX內的服務(S):

Customer c = customerRepository.GetCustomerById(int customerId) 

我也傾向於有我的資料庫實現一個接口,可以很容易地模擬數據訪問層,而不必調用像WCF服務/數據庫(單元測試)的外部依賴關係

1

我想保留單獨的Service Layer來處理此問題。此服務層中的類將與其他數據源(WCF服務/其他Repositary/ADO.NET層etcc)交互,並將這些域對象轉換爲相應的ViewModel,並在需要時將它們返回給我的Controller Action。

namespace YourProject.Services 
{ 
public class UserService 
{ 

    public UserViewModel GetUser(int id) 
    { 
    UserViewModel objVM=new UserViewModel(); 

    User objRealUser=GetUserFromWCFService(id); 
    if(objUser.IsValid) 
    { 
     objVM.FirstName=objUser.FirstName; 
     // Assign the other properties to the View model or use Automapper. 
    } 
    return objVM; 
    }  

} 
}