C# ASP.NET – Wrapping Controller/ApiController to Remove Boilerplates

asp.netcgeneric-programminginheritance

We are aiming to reduce code noise that would be common for all Controllers such as basic CRUD.

public interface IGenericController<T, Y> where T : BaseMaster
{
    IEnumerable<T> Get();

    T Get(Y code);

    HttpResponseMessage Post(T entity);

    T Put(T entity);

    T Delete(Y code);
}

this would be use as

public class AuditController : GenericController<AuditRepository, int>

We could also use Composition over Inheritance approach here for code reuse however we there will still be code noises, so we make this as a choice.

I am a bit hesitant on wrapping existing .net base classes. One thing I could be sure is that the virtual methods are no longer expose for overriding.

Would there be any further complication on this approach?

Best Answer

Its fairly common to use a custom BaseController from which your other controllers inherit rather than Controller. I dont think there is any particular danger here.

However! I have to agree that its not good practice. Your approach suggests that you will go all the way down to generic repositories.

But at some point you are going to have to deal with differing business logic, or input parameters between the different controllers.

Rather than bury that conditional in the inheritance tree, its best to have it up front in your controller or service layer. (do you have a service layer?)

Alternatively if you really are just exposing a generic repo with identical methods, then you could do that in a single controller, parsing the type out of the route


When I say a single controller I mean something like...

[Route="/{resourceType}/{id}"]
object Get(string resourceType, string id)
{
    var repo = repoFactory.GetForType(resourceType);
    return repo.Get(id)
}

That single controller and action is called for all your http://myapi/myresource/123

Related Topic