What does this error message mean?

Yusuf 681 Reputation points
2021-09-25T11:07:22.003+00:00

Hi

I'm working on this project and it's working.

But when I convert comments to code

using Microsoft.AspNetCore.Mvc.RazorPages;  
using Microsoft.EntityFrameworkCore;  
using Microsoft.Extensions.Logging;  
using System.Collections.Generic;  
using System.Threading.Tasks;  
using WebApplication10.Data;  
using WebApplication10.Model;  
  
namespace WebApplication10.Pages  
{  
    public class IndexModel : PageModel  
    {  
          
        //private readonly ILogger<IndexModel> _logger;  
        //public IndexModel(ILogger<IndexModel> logger)  
        //{  
        //    _logger = logger;  
        //}  
  
        private readonly WebApplication10Context _db;  
        public IndexModel(WebApplication10Context db)  
        {  
            _db = db;  
        }  
  
        public IEnumerable<Book> Books { get; set; }  
        public async Task OnGet()  
        {  
            Books = await _db.Book.ToListAsync();  
        }  
    }  
}  

I get this error.

InvalidOperationException: Multiple constructors accepting all given argument types have been found in type 'WebApplication10.Pages.IndexModel'. There should only be one applicable constructor.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,138 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,201 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. AgaveJoe 26,186 Reputation points
    2021-09-25T11:24:54.07+00:00

    What does this error message mean?

    Only one constructor executes. The dependency injection framework has no idea which constructor to execute. Add one constructor with both parameters you intend to inject. I think you'll be very interested in reading .NET 5 dependency injection fundamentals which covers standard patterns.

    public class IndexModel : PageModel  
     {  
         private readonly ILogger<IndexModel> _logger;  
         private readonly WebApplication10Context _db;  
           
         public IndexModel(WebApplication10Context db, ILogger<IndexModel> logger)  
         {  
             _db = db;  
             _logger = logger;  
         }  
      
         public IEnumerable<Book> Books { get; set; }  
         public async Task OnGet()  
         {  
             Books = await _db.Book.ToListAsync();  
         }  
     }  
    
    1 person found this answer helpful.