简体   繁体   中英

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";
                     }
                 }

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

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

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!!!!!

@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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM