I'm creating my first Web API and currently have the following code:
public interface IRepository<T> where T : class
{
T GetById(Int32 id, VehicleTypeEnum type);
}
public class VehicleRepository : IRepository<Vehicle>
{
public VehicleRepository(DbContext dataContext) {}
public Vehicle GetById(Int32 id, VehicleTypeEnum type)
{
try
{
switch (type)
{
case VehicleTypeEnum.Car:
// connect to WcfService1 to retrieve data
case VehicleTypeEnum.Truck:
// connect to WcfService2 to retrieve data
case VehicleTypeEnum.Motorcycle:
// connect to Database to retrieve data
}
}
catch (Exception ex)
{
// log exception
}
}
}
public class VehicleController : ApiController
{
private readonly IVehicleRepository _repository;
public VehicleController(IVehicleRepository repository)
{
_repository = repository;
}
// GET api/vehicle/5
public Vehicle GetVehicle(int id, VehicleTypeEnum type)
{
return _repository.GetById(id, type);
}
}
As you can see in the GetById method of the VehicleRepository, I need to call a different service depending on the Enum value passed in. I would like to avoid having this switch case in each and every method.
I was told that I can use IoC / Dependency Injection... already tried to search simple examples but cannot get my head around the concept.
Can anyone enlighten me on how I can implement this simply please?
switchin a helper class?