Search code examples
c#.netasp.net-corecontroller

How to reuse methods in ApiController?


I have an object called Garage that can have many Vehicle objects. In the ApiController "GaragesController" I have the following methods:

   [ProducesResponseType(typeof(IList<VehicleResponse>), 200)]
   [HttpGet("{GarageId}/vehicles")]

    public async Task<IActionResult> GetGarageVehicles([FromQuery] FindVehiclesByGarageQuery query)
    {
        return Ok(await _findVehiclesByGarageQueryHandler.Handle(query));
    }

    [ProducesResponseType(typeof(VehicleResponse), 200)]
    [HttpGet("{garageid}/vehicles/{vehicleid}")]

    public async Task<IActionResult> GetDepotGarage(int garageid, int vehicleid)
    {
        
        return Ok(await _findVehicleByGarageQueryHandler.Handle(new FindVehicleByGarageQuery
        {
            GarageId= garageid,
            VehicleId = vehicleid

        }));
    }

I also have an object Called Depot that can contain many Garages. In the upcoming DepotsController, is there any way to "reuse" the methods in the GarageController, or do I have to to it all over again?


Solution

  • You can encapsulate the reusable piece of code into a method and place it in a class which is accessible to your controllers.

    Thereafter, you can create separate action methods with specific routes in the different controllers and invoke the reusable method (placed in that separate class), within the body of the action method as per need.

    This way you can reuse code and keep the routes and actions different for different controllers.