1

I'm currently building an API Application for my Website in order to make the connection between my Website and my Database. Also i'm using a 3 layer architecture (I have 1 Controller, that has the HttpTrigger from Azure Function inside, i have a Service that is used to call my database queries, and i have a repository that is where i do my queries to database).

So this structure is working this way: Controller (HttpTrigger) - Calls the Service Service calls the repository Repository - Performs the query to my database and returns the values to service.

I'm trying to implement the concept of Dependency Injection and i do think it is working, since i've added a Startup.cs file with the call to my Interface and to the class the Implements my Interface.

The problem is: On controller, i'm initializing my interface, but when i try to call a method from my Service, it is throwing the following error: "An object reference is required for the non-static field, method or property 'AlunoController.alunoService'"

These are my files:

IAlunoService - Interface

public interface IAlunoService
{
    public Task<IList<AlunoModel>> ObterAlunos();
}

AlunoService - That implements the Interface Methods

public class AlunoService : IAlunoService
{
        #region DI services
        private readonly ILogger<AlunoService> logger;
        private readonly IAlunoRepository alunoRepository;

        public AlunoService(
            ILogger<AlunoService> logger,
            IAlunoRepository alunoRepository
            )
        {
            this.logger = logger;
            this.alunoRepository = alunoRepository;

        }
        #endregion

        public async Task<IList<AlunoModel>> ObterAlunos()
        {
            Utility.WriteLog(Utility.LogType.Information, "Service - ObterAlunos Called");

            var alunos = await alunoRepository.ObterAlunos();
            if(alunos == null)
            {
                throw new NullReferenceException();
            }

            return alunos;
        }
}

Startup.cs File

    [assembly: WebJobsStartup(typeof(ProjetoGlobalHajime_APILayer.Startup))]
namespace ProjetoGlobalHajime_APILayer
{
    public class Startup : IWebJobsStartup
    {
        public void Configure(IWebJobsBuilder builder)
        {
            builder.Services.AddScoped<IAlunoService, AlunoService>();
builder.Services.AddScoped<IAlunoRepository, AlunoRepository>();
        }
    }
}

AlunoController - That is where i'm having the issue

#region DI Services
    private readonly IAlunoService alunoService;
    #endregion

    public AlunoController(IAlunoService alunoService, ILogger<AlunoController> log)
    {
        this.alunoService = alunoService;
        IAlunoService alunoService1 = alunoService;
    }

    /// <summary>
    /// Retorna todos os alunos
    /// </summary>
    /// <param name="req"></param>
    /// <param name="log"></param>
    /// <returns></returns>
    [FunctionName("Aluno_Obter_Lista")]
    public static async Task<IActionResult> Alunos_ObterLista(
        [HttpTrigger(AuthorizationLevel.Function, "get", Route = "Aluno/ObterLista")] HttpRequest req,
        ILogger log)
    {
        log.LogInformation("Alunos_Obter_Lista Called");

        try
        {
            alunoService.ObterAlunos(); //----------> The error is being thrown here
        }
        catch (Exception ex)
        {
            log.LogError("[ERROR] " + ex.InnerException);
        }

        return new OkObjectResult("Anything");
    }

IAlunoRepository

public interface IAlunoRepository
    {
        public Task<IList<AlunoModel>> ObterAlunos();
    }

AlunoRepository

public class AlunoRepository : IAlunoRepository
    {
        public async Task<IList<AlunoModel>> ObterAlunos()
        {
            List<AlunoModel> listaAlunos = new List<AlunoModel>();
            using (SqlConnection connection = new SqlConnection(Utility.ConnectDatabaseString()))
            {
                await connection.OpenAsync();
                SqlCommand command = new SqlCommand("SELECT * FROM dbo.aluno", connection);
                using (SqlDataReader reader = await command.ExecuteReaderAsync())
                {
                    while (reader.Read())
                    {
                        try
                        {
                            listaAlunos.Add(new AlunoModel { Id = reader.GetInt32(0), Nome = reader.GetString(1), Data_Nascimento = reader.GetDateTime(2), Contacto = reader.GetString(3), Morada = reader.GetString(4), C_Postal = reader.GetString(5), Localidade = reader.GetString(6), Email = reader.GetString(7), Nif = reader.GetInt32(8), Recolha_Imagem = reader.GetByte(9), Atestado_Medico = reader.GetByte(10), Protecao_Dados = reader.GetByte(11), Cartao_Cidadao = reader.GetString(12), Validade = reader.GetDateTime(13), Fk_encarregado_educacao_id = reader.GetInt32(14), Fk_turma_id = reader.GetInt32(15) });
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("[ERROR] Exception Found: " + ex.InnerException);
                            Utility.WriteLog(Utility.LogType.Error, ex.InnerException.ToString());
                        }
                    }
                }
                connection.Close();

            }
            return listaAlunos;
        }
    }

I'm trying very hard to understand why this is not working since on my Controller Constructor i'm calling the interface. Although it is not working.

The strange part is that i'm using the same "way" to call and implement the interface on Service File and, for example, the "alunoRepository" i can call without any problem.

Could you please help me solve this issue? I'm currently studying on College and this is related to one of my final projects.

Edit: Printscreen of the error:

enter image description here

  • @Nkosi You are right. I have updated my question, thanks. Edit: i have also added the AlunoRepository to my Startup.cs but the error persists. – Nuno Afonso Silva Feb 06 '21 at 18:59
  • @Nkosi in fact my issue was being inside a static method trying to call a non-static method. I've figured it out. Thank you for your inputs :) – Nuno Afonso Silva Feb 06 '21 at 20:08

2 Answers2

2

I've figured what was the issue. Been looking at it all day and didn't realize that i was calling a non-static method inside a static method.

Inside my Controller i've just removed the "static" and it worked like a charm. Thanks everyone for your inputs.

0

If you do not use a reader properly you will get null objects. You have to use async reader this way:

 while (await reader.ReadAsync()) {
    for (int i = 0; i < reader.FieldCount; i++) {
         // Process each column as appropriate
          object obj = await reader.GetFieldValueAsync<object>(i);
        }
}

and since you are using async methods everywhere , so you have to call Alunos_ObterLista.ObterAlunos as async:


var resultList = await alunoService.ObterAlunos();

.....
return new OkObjectResult(resultList );

Serge
  • 40,935
  • 4
  • 18
  • 45
  • Thank you for your answer. I appreciate it and i know that, but the error is not related with the "await". The error is: An object reference is required for the non-static field, method or property when i try to call it. I can't understand why because inside the DI and the construct im calling the interface. – Nuno Afonso Silva Feb 06 '21 at 19:17
  • @NunoAfonsoSilva - see my update – Serge Feb 06 '21 at 19:32
  • Awesome. Thank you for pointing this out, but my Main issue persists.. Could you please take a look at the main point of this question? – Nuno Afonso Silva Feb 06 '21 at 19:34
  • @NunoAfonsoSilva Yes , if you do not use a reader properly you will get null objects. – Serge Feb 06 '21 at 19:36
  • When do you get this exception? If you have a problem with DI the exception goes immediately, before the first screen. – Serge Feb 06 '21 at 19:42
  • i'm getting this error in compiler. It doesn't even compile I do get this error when inside my controller i try to call AlunoService like this: var result = await alunoService.ObterAlunos(); the error appears on "alunoService" – Nuno Afonso Silva Feb 06 '21 at 19:46
  • No it's not sintax error, since the method inside the interface appears after writing it. It's not a runtime error also, since i'm saying that the error is being underlined. My code about the SQL Queries also works, i understand that it can be improved. thank you. have a nice day. – Nuno Afonso Silva Feb 06 '21 at 19:56
  • The main focus is about Dependency Injection and not about calling Async methods or performing SQL queries. – Nuno Afonso Silva Feb 06 '21 at 19:56
  • Still not helping me at all. – Nuno Afonso Silva Feb 06 '21 at 20:06
  • Found the solution. I just can call non-static members from static members... That was the problem, i'm sharing this with you FYI. Have a nice day. – Nuno Afonso Silva Feb 06 '21 at 20:07