首页 > 解决方案 > 控制器抛出我无法捕获的错误(MVC5、C#、EF6)

问题描述

我接手了一个使用 EF6 和 MVC 编写的项目,这两个我都不太熟悉。我已经设法完成了大部分正在发生的事情,但我需要创建一个新的数据表/实体/服务/dto/控制器和视图。同样,这大部分似乎都可以,但是控制器不起作用,我无法弄清楚如何捕获引发错误的位置或问题所在的位置。

基本情况是控制器有一个默认操作,即返回一个简单的字符串(稍后它将返回一个页面,但我一直在删除不必要的位以确定问题所在)。控制器的构造函数有两个参数,我理解它们是通过依赖注入工厂传递给构造函数的——这个项目正在使用 Ninject。

这是服务代码:

public class NewThingService
{
    private readonly IRepository<NewThing> repoNewThing;

    public NewThingService(IRepository<NewThing> _repoNewThing)
    {
        this.repoNewThing = _repoNewThing;
    }

    public void Save(NewThing entity)
    {
        if (entity.Id == 0)
        {
            repoNewThing.Insert(entity);
        }
        else
        {
            repoNewThing.Update(entity);
        }
    }

    public void Delete(int id)
    {
        repoNewThing.Delete(id);
    }

    public void Dispose()
    {
        if (repoNewThing != null)
        {
            repoNewThing.Dispose();
        }
    }
}

这是服务接口代码:

public interface INewThingService : IDisposable
{
        void Save(NewThing entity);
        void Delete(int id);
}

这是控制器代码:

public class TestController : BaseController
{
        private readonly INewThingService newThingService;
        private readonly IExistingThingService existingThingService;

        public TestController(INewThingService _newThingService, IExistingThingService _existingThingService)
        {
            this.newThingService = _newThingService;
            this.existingThingService = _existingThingService;
        }

        [HttpGet]
        public ActionResult Test(DataTableServerSide model)
        {
            return Json("Hello", JsonRequestBehavior.AllowGet);
        } 
}

ExistingThing 服务是我继承的代码的一部分。NewThing 服务是我添加的。

如果我按上述方式运行代码,请求将重新路由到错误处理程序,但实际上似乎没有任何关联的错误。如果我通过删除 _newThingService 参数来更改控制器构造函数,它工作正常。如果我用代码中已经存在的另一个服务替换 _existingThingService 参数,那也可以正常工作。

因此,我的新服务的构造或传递给控制器​​构造函数的方式存在问题,但它似乎不是这样的错误 - 至少不是 VS 可以捕获的错误。

出了什么问题,或者我如何找出问题所在?

已编辑----

NewThingService的Ninject注册

private static void RegisterServices(IKernel kernel)
{
      kernel.Bind<ProjectDbContext>().ToSelf().InRequestScope();
      kernel.Bind(typeof(IRepository<>)).To(typeof(Repository<>));
      kernel.Bind(typeof(INewThingService)).To(typeof(NewThingService));
}

IRepository 声明似乎是通用的,而不是特定于每个实体的声明:

public interface IRepository<TEntity> where TEntity : class
{
    TEntity FindById(object id);
    void InsertGraph(TEntity entity);
    void Update(TEntity entity);
    TEntity Update(TEntity dbEntity, TEntity entity);
    void Delete(object id);
    void Delete(TEntity entity);
    void Insert(TEntity entity);
    RepositoryQuery<TEntity> Query();
    void Dispose();
    void ChangeEntityState<T>(T entity, ObjectState state) where T : class;
    TEntity SetValues(TEntity dbEntity, TEntity entity);
    void SaveChanges();
}

标签: c#model-view-controllerconstructorcontroller

解决方案


推荐阅读