1

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.

G_Man
  • 1,323
  • 2
  • 21
  • 33

1 Answers1

3

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());
    }
 }
Oliver
  • 8,794
  • 2
  • 40
  • 60
  • Thank you this has me on the right track. Although adding the parameterless constructor adds an error. Error 6 Cannot create an instance of the abstract class or interface 'SoapService' – G_Man Mar 20 '13 at 18:20