无法使用存储库模式

时间:2017-10-08 19:46:28

标签: asp.net-mvc interface repository-pattern

我目前正在学习接口和存储库模式,并且遇到困难。我有域类“VehicleMake”

  public class VehicleMake
{
    public VehicleMake()
    {

    }

    [Key]
    [Column(Order = 1)]
    public int Id { get; set; }

    [Required]
    [StringLength(50)]
    public string Name { get; set; }

    public virtual ICollection<VehicleModel> VehicleModels { get; set; }
}

我还有一个接口“IVehicleRepository”

    public interface IVehicleRepository
{
    IEnumerable<VehicleMake> All { get; }
}

和实现该接口的类“VehicleRepository”

public class VehicleRepository : IVehicleRepository
{
    private readonly VehicleDbContext _context;

    public VehicleRepository(VehicleDbContext context)
    {
        _context = context;
    }

    public IEnumerable<VehicleMake> All => _context.VehicleMakes;
}

我的DbContext类正在关注

public class VehicleDbContext : DbContext
{
    public VehicleDbContext() : base("VehicleDbContext")
    {

    }

    public DbSet<VehicleMake> VehicleMakes { get; set; }
    public DbSet<VehicleModel> VehicleModels { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

    }

}

我的“VehicleController”正在关注

 public class VehicleController : Controller
{
    private readonly IVehicleRepository _vehicleRepository;

    public VehicleController()
    {

    }

    public VehicleController(IVehicleRepository vehicleRepository)
    {
        _vehicleRepository = vehicleRepository;
    }

    // GET: VehicleMakes
    public ActionResult Index()
    {
        return View(_vehicleRepository.All);
    }
}

所以问题是,当我尝试在我的控制器中检索“Vehicle Makes”时,我得到null引用异常,我不知道为什么。我是否正确实施了这个?如果没有,这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

您收到NullReferenceException,因为它正在调用您的无参数构造函数,而您没有初始化_ vehicleRepository字段。您的初始化位于构造函数中,您将传递IVehicleRepository对象。

我相信,您没有注册正确获取实例的依赖注入框架。因此,您只需在默认构造函数中初始化_ vehicleRepository

public class VehicleController : Controller
{
     private readonly IVehicleRepository _vehicleRepository;

     public VehicleController()
     {
              _vehicleRepository = new VehicleRepository();
     }

     // GET: VehicleMakes
     public ActionResult Index()
     {
          return View(_vehicleRepository.All);
     }
}

按以下方式更改VehicleRepository以支持默认构造函数:

public class VehicleRepository : IVehicleRepository
{
    private readonly VehicleDbContext _context;
    public VehicleRepository() : this(new VehicleDbContext())
    {
    }
    public VehicleRepository(VehicleDbContext context)
    {
        _context = context;
    }

    public IEnumerable<VehicleMake> All => _context.VehicleMakes;
}