ASP .NET MVC 2中的Web服务

时间:2010-11-30 17:32:04

标签: asp.net asp.net-mvc web-services asp.net-mvc-2 mvvm

我正在使用ASP .NET MVC2来创建一个数据驱动的网站。部分功能请求还用于创建可重用的Web服务,以公开一些最终用户可以创建mashup的数据和业务逻辑。将有大量用户在我们组织内外使用它。

到目前为止,我构建了与数据库通信的应用程序(使用实体框架ORM),处理和显示数据(使用模型视图视图模型模式)。这部分对网站部分很简单。

至于webservices部分,我正在研究使用WCF来创建Web服务。我应该将WCF数据服务创建为单独的项目。我猜我应该能够重用控制器中的一些代码。

在网站部分我应该调用这些Web服务并将它们用作模型吗?任何最佳做法?

作为asp .net新手的somoeone,任何指向正确方向的指针都将非常感激。

1 个答案:

答案 0 :(得分:2)

您可以使用单独的Web应用程序来托管Web服务。这将使您可以在IIS中的单独虚拟目录中托管MVC应用程序和WCF服务。编写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服务项目,您可以添加服务引用,实现{{ 1}}存储库并指示您的DI框架使用此实现而不是现在将转到Web服务的ProductsRepositoryWcf

相关问题