您可以使用單獨的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
。
是否有任何特定的原因需要創建一個WCF服務,並且不能僅僅通過返回`JsonResult`作爲視圖輸出來使用MVC作爲你的web服務? – KallDrexx 2010-11-30 17:56:40
@KallDrexx:缺乏靈活性是一個原因。 – 2010-11-30 19:36:56