简体   繁体   中英

MVC with WCF service design

Being new to MVC, and WCF (somewhat), I'd like to ask a design question. I have an MVC application, with a simple screen. I need to call a WCF service, which returns a reply object type. To separate the WCF calls from my MVC app, I have created a ServiceProxy dll, which exposes a method called RegisterWithService , passing it an IP address.

So, MVC app, calls

ServiceProxy.RegisterWithService(xxx.xxx.xxx.xxx);

The method then creates a RegistrationRequest object, and sends that to the WCF service. The reply (a RegisterResponce object) replies with an object.

My question is, is it OK to pass that object back to the MVC controller to deal with, or should I create some form of DTO... so that the ServiceProxy creates a new object type (maybe, RegistrationDTO , which has the same fields as the WCF reply object, and passes that back to the MVC app? That, I guess, makes the MVC non-reliant on the WCF objects... so a change in the service contract would only cause a change in the proxy class I created - leaving the MVC app segregated.

Does that seem like a good design?

I think that 2 levels of objects are enough:

  1. Domain models (coming from your WCF service)
  2. View models (specific to the MVC application)

So you could use the service proxy interface that was generated for you when you imported the WCF service definition as repository layer. This interface will return your data contracts which will represent the domain models. The Controller will be responsible for calling various methods on this interface and mapping the domain models to view models that will be passed to the view.

For example:

public class HomeController: Controller
{
    private readonly IServiceProxy service;
    public HomeController(IServiceProxy service)
    {
        this.service = service;
    }

    public ActionResult Index(int id)
    {
        SomeDataContract domainModel = this.service.Get(id);
        MyViewModel model = Mapper.Map<SomeDataContract, MyViewModel>(domainModel);
        return View(model);
    }
}

Of course if your application gets more complex you could introduce an additional abstraction layer and DTOs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM