Reputation: 6666
I just recently started to experiment with .NET MVC 4.
The thing is I have a WCF service that provides data for several application and would like to use it for a site using MVC as well.
Im totally new to this, so Im wondering where the best place to connect to the WCF is. I guess that the WCF could be considered to be the model, and in that case the best way would be to place it in a controller.
But is this really correct or should the service be consumed in the model layer?
Upvotes: 1
Views: 3017
Reputation: 218732
I would like to keep a seperate Service Layer
to handle this. The classes in this service layer will interact with other datasource ( WCF service/ Other Repositary / ADO.NET layer etcc) and convert those domain objects to corresponding ViewModels and return those to my Controller Actions when they need it.
namespace YourProject.Services
{
public class UserService
{
public UserViewModel GetUser(int id)
{
UserViewModel objVM=new UserViewModel();
User objRealUser=GetUserFromWCFService(id);
if(objUser.IsValid)
{
objVM.FirstName=objUser.FirstName;
// Assign the other properties to the View model or use Automapper.
}
return objVM;
}
}
}
Upvotes: 1
Reputation: 39248
I tend to architect this using a repository pattern where the repository methods return instances of my model classes:
Inside my controller I will simply instantiate a reference to my repository and call the appropriate methods. The repository will wrap the WCF service proxy and call the service(s) inside the various repository methods
EX from CustomerController:
Customer c = customerRepository.GetCustomerById(int customerId)
I also tend to have my repositories implement an interface to make it easy to mock the data access layer without having to call external dependencies like the WCF service/database (unit tests)
Upvotes: 2