0

I'd like to use new MS Web API without having to inherit from ApiController

Ideally I'd like to create separate classes that handle only one HTTP Method and Route. For example:

// Handles GET /customer/1
public class GetCustomerHandler
{
    public object Handle(int id)
    {
        return ...;
    }
}

// Handles PUT /customer/1
public class PutCustomerHandler
{
    public object Handle(NewCustomerForm form)
    {
        return ...;
    }
}

I imagine that System.Web.Http has plenty of extension points to allow this approach, but I can't find the appropriate documentation. Can someone point me in the right direction please?

j0k
  • 22,600
  • 28
  • 79
  • 90
Andrew Davey
  • 5,441
  • 3
  • 43
  • 57
  • This is not the intended approach to use ApiController. Is there particular reason to do this? You can always call other classes to in your main controller so would that work?# – Aliostad Jul 18 '12 at 09:22
  • I'm experimenting with a stricter SRP approach to my code. The code that handles getting data is completely different to the code that updates data, so I don't see why they should be in the same class. – Andrew Davey Jul 18 '12 at 09:37

1 Answers1

0

This is not the intended approach to use ApiController.

I suggest, if you need to do this, you build it on the top of normal routing/action selection. I mean you could have a controller that calls other classes for such implementation. One such prototype using a functional approach could be below:

public abstract class HubController<T>
{

    private Func<int, object> _getHandler;
    private Func<T, object> _putHandler;

    public HubController(Func<int, object> getHandler, Func<T, object> putHandler
        // ... delete and post handlers too
        )
    {
        _putHandler = putHandler;
        _getHandler = getHandler;
    }

    public object Get(int id)
    {
        return _getHandler(id);
    }

    public object Put(T t)
    {
        return _putHandler(t);
    }

    // ... also Post and Delete
}

public class CustomerControler : HubController<Customer>
{
    public CustomerControler(Func<int, object> getHandler, Func<Customer, object> putHandler) : base(getHandler, putHandler)
    {
    }
}

The delegates could be just delegates or implementation of interfaces although I prefer delegate since "interface with a single method is a delegate".

Aliostad
  • 80,612
  • 21
  • 160
  • 208