I currently have a controller with several actions, but I’ve run into a problem with a single action that seems to require the instantiation of the repository within the action itself, or else I get a NullReferenceException during runtime–the action itself doesn’t appear to be any different than the other actions in the controller. This is what I have so far:
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);
}
Is there a particular reason why I need the repository instantiated in the action for it to work? This is the error I get if I comment it out:
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.Exception Details: System.NullReferenceException: Object reference not
set to an instance of an object.Source Error:
Line 155: //PatentRepository patentRepository = new
Proj.Data.PatentRepository(); Line 156: USPTOPatent
usptoPatent = patentRepository.GetPatent(id); Line 157:
return PartialView(“DetailsPartial”, usptoPatent); Line 158: }
Your default constructor assigns the result of the
newto a local variable, that will take precedence over the one declared at class scope. Therefore, when the controller is created in this way, the member variableparentRepositoryhas not been initialised.Change the default ctor to: