【发布时间】:2014-04-04 14:30:20
【问题描述】:
我正在创建我的第一个 Web API,目前有以下代码:
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);
}
}
正如您在 VehicleRepository 的 GetById 方法中看到的,我需要根据传入的 Enum 值调用不同的服务。 我想避免在每一种方法中都有这个开关盒。
有人告诉我,我可以使用 IoC / 依赖注入...已经尝试搜索简单的示例,但无法理解这个概念。
谁能告诉我如何简单地实现这一点?
【问题讨论】:
-
你不能把
switch移动到一个助手类吗?
标签: c# .net asp.net-mvc-4 asp.net-web-api