1
votes

Can not figure out what I am doing wrong.

Controller Code.

public class HomeController : Controller
{
    private readonly SoapWebService _db;

    public HomeController(SoapWebService db)
    {
        _db = db;
    }

    public ActionResult Index()
    {
        return View(_db.GetAllItems("APIKey").ToList());
    }
 }

View Code

@model IEnumerable<ProjectName.ServiceName.ItemName>

@foreach (var item in Model) {
     @Html.DisplayFor(item => item.Title)
}

Error

No parameterless constructor defined for this 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.MissingMethodException: No parameterless constructor defined for this object.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

1
What DI tool are you using? StructureMap? You don't even mention that. - manojlds
Is this a typo: @Html.DisplayFor(modelItem => item.Title)? Should it be @Html.DisplayFor(item => item.Title)? - Trey Gramann
That was a typo and I am not using a dependency injector maybe that is where I am going wrong here. - G_Man
Should not need IoC on this yet. I think @Oliver fixes your 1st problem. Then you may have another. - Trey Gramann

1 Answers

3
votes

Without using dependency injection functionality (framework or hand-spun), your controller cannot be instantiated because there is no parameterless constructor.

In your case, a dependency injector would create an instance of SoapWebService to pass into the controllers only constructor.

Without using DI, you will need a parameterless constructor that will instantiate any dependencies itself:

public class HomeController : Controller
{
    private readonly SoapWebService _db;

    public HomeController()
        : this(new SoapWebService()) { }

    public HomeController(SoapWebService db)
    {
        _db = db;
    }

    public ActionResult Index()
    {
        return View(_db.GetAllItems("APIKey").ToList());
    }
 }