3

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?

1
  • Couldn't you just move switch in a helper class? Commented Apr 4, 2014 at 14:43

1 Answer 1

1

This looks like a straightforward example of the problem of run-time selection or mapping of one of several candidate Strategies.

There are at least three ways to do this in a container-agnostic way:

My personal preference is the Partial Type Name Role Hint.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.