Ikhwan
Ikhwan

Reputation: 353

Automatically Wrap a Controller Around a Service in ASP.NET MVC

The question title might not be clear but what I want to do is something like this:

This is how I layer out my app

App.Domain App.Services App.Web

What I want is, if I request something like /api/OrderProcessor/GetAllOrder it will call method GetAllOrder in App.Services.OrderProcessorService.

The method will return an IList<Order> and i would like it to be serialized into JSON according to a certain format (I'm using ExtJS actually), to maybe something like:

{ 
  success: true,
  totalCount: 10,
  list: [ { ... }, { ... } ]
}

I can go on and make the Services as Controllers, but I don't want the service layer to be tainted with presentation stuff.

How can I go about making a wrapper controller like this?

I don't want to attach any attributes on the Service class itself, and would probably be nice if I can configure it using IoC, where by maybe later on I want the output be XML or maybe the ability to use a DTO class instead of the original Domain class.

Any idea?

Upvotes: 3

Views: 312

Answers (2)

Andrew Matthews
Andrew Matthews

Reputation: 3146

You could use something like PostSharp's OnMethodInvocationAspect to intercept every call to your controller method and act as a relay to similarly named methods on a designated proxy object...

Upvotes: 0

Kevin Swiber
Kevin Swiber

Reputation: 1556

It's sounds like you're trying to make a RESTful service.

Using a RESTful service, the /api/OrderProcessor/GetAllOrders URI would return your JSON objects.

If that's the case, I would use WCF instead of ASP.NET MVC.

To get started with WCF, REST, and JSON, check out the WCF REST Starter Kit Preview 2 on Codeplex. There's a quick example of returning JSON from a WCF service in this blog post I found by Ben Dewey.

Good luck!

Upvotes: 2

Related Questions