Tuesday, October 16, 2018

Using an abstract class to encapsulate API controller behavior. Is it a good practice?

In my new project I've been tasked with writing the API with which the front end will consult to receive model data. It will consist purely of simple get and post methods, which will all be mostly identical except for the lines in which the repository for the respective model will be called. For example: ` UnitOfWOrk.ModelObjectRepository.GetAll() `

So I figured I'd make all the API controllers inherit from a single abstract class of which this is a shortened example:

[Route("api/v1/[controller]")]

public abstract class ABMApiController<T> : Controller where T : class {

protected readonly IUnitOfWork _unitOfWork;

public ABMApiController (IUnitOfWork unitOfWork) { this._unitOfWork = unitOfWork; }

[HttpGet("{id}")]

public IActionResult Get (int id) {

var workingModel = WorkingRepository.Get(id);

return Json(workingModel);

}

protected abstract IRepository<T> WorkingRepository { get; }

}

And then the inheriting class would simply override the WorkingRepository method with:

` get { return this._unitOfWork.ModelObjectRepository } `

I would like to have your opinions on wheter this is good practice and if it can be improved. I apologize in advance for any vagueness or stuff I may have mistakenly omitted. I've only started with .Net core 2 months ago. Thanks.

Using an abstract class to encapsulate API controller behavior. Is it a good practice? Click here
  • Blogger Comment
  • Facebook Comment

0 comments:

Post a Comment

The webdev Team