Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency injection in simple ASP.NET Web API

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?

like image 819
Dave Avatar asked Mar 31 '26 18:03

Dave


1 Answers

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:

  • Use a Metadata Role Hint
  • Use a Role Interface Role Hint
  • Use a Partial Type Name Role Hint

My personal preference is the Partial Type Name Role Hint.

like image 183
Mark Seemann Avatar answered Apr 03 '26 08:04

Mark Seemann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!