I have the following code in a controller which, when executed, displays the view to the user in the browser:
public class PlayerController : Controller
{
private readonly IPlayerRepository repo;
public IActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(Player person)
{
var lastName = person.LastName;
var firstName = person.FirstName;
var callPlayer = new PlayerInit();
var returnPlayer = callPlayer.SetUpPlayer(lastName, firstName);
return View();
}
}
When I add this code, an exception is thrown:
public PlayerController(IPlayerRepository repo)
{
this.repo = repo;
}
This is the exception that gets thrown:
I have similar code in a different controller and I am able to run that controller to access a mySql database via dapper and display the results to the view. Im not sure why the code in this particular controller is having an issue.
Thank you!
CodePudding user response:
Usually this error is caused because in the Startup.cs file the ConfigureServices method does not contain the code that will inject the dependency to the container.
public void ConfigureServices(IServiceCollection services)
{
.... OMMITED
services.AddScoped<IPlayerRepository, PlayerRepository>();
.... OMMITED
}
You can also take a look to the documentation on how all the dependency injection works in dotnet starting here.