Webservices in ASP .NET MVC2
I am using ASP .NET MVC2 to create a data driven web site. Part of the feature request is also to create reusable web services to expose some of the data and business logic using which end users can create mashups. There will be a significant amount of users using it within and outside our organization.
So far I have built the application that communicates to the database (using the entity framework ORM), processes and displays the data (using the model view view model pattern). This part has been straightforward for the website part.
As for the webservices part, I am looking into using WCF to create the web services. Should I create WCF data services as a separate project. I am guessing I should be able to reuse some of the code in the controller.
In the website part should I call these web services and use them as the model? Any best practi开发者_JS百科ces?
As somoeone new to asp .net, any pointers towards the right direction would be greatly appreciated.
You could use a separate web application for hosting the web services. This will give you the possibility to host your MVC application and WCF service in separate virtual directories in IIS. Once you wrote the web service you could generate a client proxy and then in the client application you could use a repository:
public interface IProductsRepository
{
IEnumerable<Person> GetProducts();
}
and then have a specific implementation of this repository that will fetch the data from your WCF service:
public class ProductsRepositoryWcf
{
public IEnumerable<Person> GetProducts()
{
using (var client = new YourWebServiceClient())
{
// call the web service method
return client.GetProducts();
}
}
}
And finally inject this repository into the constructor of your controller which might look like this:
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);
}
}
As you can see now the controller is completely decoupled by the way data is fetched. All it cares is that it respects the given contract (IProductsRepository interface). Using your favorite DI framework you could easily switch the implementation.
By the way if your code resembles mine, theonly thing that you should change in your current MVC application is to externalize the models and data access layers into a separate WCF service project which you would add service reference to, implement the ProductsRepositoryWcf
repository and instruct your DI framework to use this implementation instead of the ProductsRepositorySql
which would now go to the web service.
精彩评论