Shashi
Shashi

Reputation: 29

MVC:No parameterless constructor defined for this object

Server Error in '/' Application. No parameterless constructor defined for this object.How can I resolve this issue. I created one folder in that created interface ICompanyService and class CompanyService.

Controller:

         public class HomeController : Controller
         {
               private ICompanyService icompanyService;
               public HomeController(ICompanyService icompanyService)
              {
                 this.icompanyService = icompanyService;
               }
                public ActionResult Index()
              {     
                 ViewBag.CompanyName = this.icompanyService.GetCompany();
                return View();
              }
         }

ICompanyService:

                 public interface ICompanyService
                {
                 string GetCompany();
                }

CompanyService:

                   public class CompanyService
                   {
                      public string GetCompany()
                     {
                         return "Msc";
                     }
                 }

Upvotes: 0

Views: 2826

Answers (3)

Shahzad Khan
Shahzad Khan

Reputation: 530

@ravi please use dependency injection, so what service will automatically initialize your service constructor without defined constructor logic, the dependency inject handle and initialize you service object. don't worry about initialization.

below i have mention the link for IoC and i hope your issue will resolve soon. https://github.com/quozd/awesome-dotnet/blob/master/README.md#ioc

Upvotes: 0

BV Winoya
BV Winoya

Reputation: 345

You need to include below constructor to your controller,

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

So your entire controller code looks like below,

    public class HomeController : Controller
{
    private ICompanyService icompanyService;

    public HomeController() : this(new CompanyService())
    {
    }
    public HomeController(ICompanyService icompanyService)
    {
        this.icompanyService = icompanyService;
    }
    public ActionResult Index()
    {
        ViewBag.CompanyName = this.icompanyService.GetCompany();

        return View();
    }
}

This will solve your issue.

Happy coding!!!!!

Upvotes: 1

Amin Golmahalleh
Amin Golmahalleh

Reputation: 4216

CompanyService Class Should Inherits From ICompanyService Interface. Please Study About Dependency Injection In .NET .

 public class CompanyService : ICompanyService
                   {
                      public string GetCompany()
                     {
                         return "Msc";
                     }
                   }

Upvotes: 0

Related Questions