2010-11-30 110 views
1

我使用ASP .NET MVC2創建數據驅動的網站。功能請求的一部分也是創建可重用的Web服務,以公開使用哪些最終用戶可以創建混搭的一些數據和業務邏輯。我們組織內部和外部會有大量用戶使用它。ASP.NET中的Web服務MVC2

到目前爲止,我已經構建了與數據庫通信的應用程序(使用實體框架ORM),處理和顯示數據(使用模型視圖視圖模型模式)。這部分對於網站部分來說很簡單。

至於webservices部分,我正在研究使用WCF創建Web服務。我應該創建WCF數據服務作爲一個單獨的項目。我猜測我應該能夠重用控制器中的一些代碼。

在網站部分我應該調用這些Web服務並將它們用作模型?任何最佳實踐?

作爲somoeone新的asp.net,任何指針正確的方向將不勝感激。

+0

是否有任何特定的原因需要創建一個WCF服務,並且不能僅僅通過返回`JsonResult`作爲視圖輸出來使用MVC作爲你的web服務? – KallDrexx 2010-11-30 17:56:40

+0

@KallDrexx:缺乏靈活性是一個原因。 – 2010-11-30 19:36:56

回答

2

您可以使用單獨的Web應用程序來託管Web服務。這將使您可以將您的MVC應用程序和WCF服務託管在IIS中的獨立虛擬目錄中。一旦你寫的Web服務,你可以生成客戶端代理,然後在客戶端應用程序,你可以使用存儲庫:

public interface IProductsRepository 
{ 
    IEnumerable<Person> GetProducts(); 
} 

,然後有一個具體的實現這個倉庫將從WCF服務獲取的數據:

public class ProductsRepositoryWcf 
{ 
    public IEnumerable<Person> GetProducts() 
    { 
     using (var client = new YourWebServiceClient()) 
     { 
      // call the web service method 
      return client.GetProducts(); 
     } 
    } 
} 

最後注入這個倉庫到你的控制器的構造函數可能是這樣的:

public class HomeController: Controller 
{ 
    private readonly IProductsRepository _repository; 
    public HomeController(IProductsRepository repository) 
    { 
     _repository = repository; 
    } 

    public ActionResult Index() 
    { 
     var products = _repository.GetProducts(); 
     // TODO: An intermediary step might be necessary to convert the Product 
     // model coming from the web service to a view model which is adapted 
     // to the given view 
     return View(products); 
    } 
} 

正如你所看到的現在控制器被數據取出的方式完全解耦。所有它關心的是它尊重給定的合同(IProductsRepository接口)。使用您最喜愛的DI框架,您可以輕鬆切換實施。順便說一句,如果你的代碼與我的相似,那麼你應該在當前的MVC應用程序中改變的唯一的事情是將模型和數據訪問層外部化到單獨的WCF服務項目中,您將添加服務引用,實現ProductsRepositoryWcf存儲庫並指示您的DI框架使用此實現,而不是現在轉到Web服務的ProductsRepositorySql