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: