C# 简单ASP.NET Web API中的依赖项注入
我正在创建我的第一个Web API,目前有以下代码:C# 简单ASP.NET Web API中的依赖项注入,c#,.net,asp.net-mvc-4,asp.net-web-api,C#,.net,Asp.net Mvc 4,Asp.net Web Api,我正在创建我的第一个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 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);
}
}
公共接口i假设,其中T:class
{
T GetById(Int32 id,VehicleTypeEnum类型);
}
公共级车辆存储库:IRepository
{
公共车辆存储库(DbContext dataContext){}
公共车辆GetById(Int32 id,车辆类型枚举类型)
{
尝试
{
开关(类型)
{
案例车辆类型枚举车辆:
//连接到WcfService1以检索数据
案例车辆类型枚举卡车:
//连接到WcfService2以检索数据
案例车辆类型列举摩托车:
//连接到数据库以检索数据
}
}
捕获(例外情况除外)
{
//日志异常
}
}
}
公共级车辆控制器:ApiController
{
私有只读iWebHiclerRepository存储库;
公共车辆控制器(iVehicler存储库)
{
_存储库=存储库;
}
//获取api/vehicle/5
公共车辆GetVehicle(内部id,车辆类型枚举类型)
{
return _repository.GetById(id,type);
}
}
正如您在VehiclerDepository的GetById方法中所看到的,我需要根据传入的枚举值调用不同的服务。
我希望避免在每种方法中都使用这种开关
我被告知我可以使用IoC/依赖注入。。。我已经尝试过搜索简单的例子,但无法理解这个概念
有谁能简单地告诉我如何实现这一点吗?这看起来像是运行时选择或映射几种候选策略之一的简单示例 以容器无关的方式,至少有三种方法可以做到这一点:
- 使用
- 使用
- 使用
我个人的偏好是部分类型名称角色提示。你不能在助手类中移动
开关吗?