Sunday, October 27, 2013

ASP.NET MVC Structure Map, No parameter less constructor defined for this object.

While using Structure Map with ASP.NET MVC there was a error "No parameter less constructor defined for this object" for the already working controller. 

 [HttpPost]
        public ActionResult CreateBranch(mBranch branch)
        {
            _service.CreateBranch(branch);
           
            return new JsonResult { Data = "Registered", JsonRequestBehavior = JsonRequestBehavior.AllowGet };

        }


The Structure map Controller factory were configured properly and once this method is commented everything working except when this post method was called the error was thrown.

Reason why it threw the exception was that the class mBranch had only once constructor with a parameter when the method is called mBranch is instantiated it there was no constructor without parameter and resulted in this error.

public class mBranch
    {
        public mBranch(int companyId)
        {
            CompanyID = companyId;

            BranchContact = new mContactInfo();
        }


             //error thrown due to this constructor was missing
        public mBranch()
        {
            BranchContact = new mContactInfo();
        }

      }

No comments: