InfinityGoesAround InfinityGoesAround - 3 months ago 20
ASP.NET (C#) Question

webapi, reading microsoft article, but contains error

I am reading this article:

https://docs.asp.net/en/latest/tutorials/first-web-api.html.

and they say. you have to put this:

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using TodoApi.Models;

namespace TodoApi.Controllers
{
[Route("api/[controller]")]
public class TodoController : Controller
{
public TodoController(ITodoRepository todoItems)
{
TodoItems = todoItems;
}
}
}


But where is
TodoItems
declared?

Do I something wrong? Or is it mistake in the article?

Because If I put this in the file:

public ITodoRepository TodoItems { get; private set; }


The error goes away. But is this correct?

Answer

It's probably mistake. You should declare it as:

    public class TodoController : Controller
    {
        private readonly ITodoRepository TodoItems;

        public TodoController(ITodoRepository todoItems)
        {
            TodoItems = todoItems;
        }
    }

Here is using dependency injection by constructor.
So, I think that declaring of TodoItems as a public property is not a good idea. It should be a private readonly field that initializing only in constructor. In other case if you going to use inheritance it might be declared as a protected.

Comments