您可以使用单独的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