需要实例化存储库或发生NullReferenceException的单个操作
本文关键字:NullReferenceException 单个 操作 实例化 存储 | 更新日期: 2023-09-27 18:12:26
我目前有一个具有多个操作的控制器,但是我遇到了一个问题,单个操作似乎需要在操作本身中实例化存储库,否则我会在运行时获得NullReferenceException—操作本身似乎与控制器中的其他操作没有任何不同。这是我目前所看到的:
public class PatentController : Controller
{
IRepositoryExtension patentRepository;
public PatentController()
{
PatentRepository patentRepository = new Proj.Data.PatentRepository();
}
//Constructor for unit test project
public PatentController(IRepositoryExtension repository)
{
patentRepository = repository;
}
public ActionResult Index()
{
return View();
}
//Other actions removed for brevity
public ActionResult DetailsPartial(string id)
{
//If this PatentRepository is removed, NullReferenceException occurs
PatentRepository patentRepository = new Proj.Data.PatentRepository();
USPTOPatent usptoPatent = patentRepository.GetPatent(id);
return PartialView("DetailsPartial", usptoPatent);
}
是否有一个特殊的原因,我需要在操作中实例化存储库以使其工作?这是我得到的错误,如果我把它注释掉:
对象引用未设置为对象的实例。
描述:在执行过程中发生未处理的异常当前的web请求。请查看堆栈跟踪了解更多信息有关错误及其在代码中的起源的信息。
Exception Details: System。NullReferenceException:对象引用不存在设置为对象的实例。
源错误:
155行://PatentRepository PatentRepository = newProj.Data.PatentRepository ();第156行:usptoppatentusptoPatent = patentRepository.GetPatent(id);157行:
返回PartialView(" detailpartial ", usptoppatent);第158行:}
您的默认构造函数将new
的结果分配给一个局部变量,该局部变量将优先于在类范围内声明的局部变量。因此,当以这种方式创建控制器时,成员变量parentRepository
尚未初始化。
将默认变量改为:
public PatentController()
{
/*PatentRepository*/ patentRepository = new Proj.Data.PatentRepository();
}
是GetPatent()
的静态方法,返回USPTOPatent
的实例?看起来这个方法不是静态的。
如果方法不是静态的,则需要实例化对象才能使用。
参见:静态成员和实例成员。
如果方法是静态的,确保它在所有代码路径上都返回一个对象。