C# 控制器错误“;“非静态字段”需要对象引用;在尝试调用接口服务时引发

C# 控制器错误“;“非静态字段”需要对象引用;在尝试调用接口服务时引发,c#,dependency-injection,interface,C#,Dependency Injection,Interface,我目前正在为我的网站构建一个API应用程序,以便在我的网站和数据库之间建立连接。 我还使用了一个3层架构(我有一个控制器,里面有来自Azure的HttpTrigger函数,我有一个用于调用数据库查询的服务,我有一个存储库,在那里我可以查询数据库) 所以这个结构是这样工作的: 控制器(HttpTrigger)-调用服务 服务调用存储库 存储库-对我的数据库执行查询,并将值返回给服务 我正在尝试实现依赖项注入的概念,我确实认为它是可行的,因为我添加了一个Startup.cs文件,其中包含对我的接口和

我目前正在为我的网站构建一个API应用程序,以便在我的网站和数据库之间建立连接。 我还使用了一个3层架构(我有一个控制器,里面有来自Azure的HttpTrigger函数,我有一个用于调用数据库查询的服务,我有一个存储库,在那里我可以查询数据库)

所以这个结构是这样工作的: 控制器(HttpTrigger)-调用服务 服务调用存储库 存储库-对我的数据库执行查询,并将值返回给服务

我正在尝试实现依赖项注入的概念,我确实认为它是可行的,因为我添加了一个Startup.cs文件,其中包含对我的接口和实现我的接口的类的调用

问题是:在控制器上,我正在初始化我的接口,但当我试图从我的服务调用一个方法时,它抛出了以下错误:“非静态字段、方法或属性'AlunoController.alunoService'需要对象引用”

这些是我的文件:

IAlunoService-接口

public interface IAlunoService
{
    public Task<IList<AlunoModel>> ObterAlunos();
}
    [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>();
        }
    }
}
#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");
    }
公共接口服务
{

公共任务如果不正确使用读卡器,将获得空对象。必须以以下方式使用异步读卡器:

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

我知道问题出在哪里了。 我看了一整天,没有意识到我在一个静态方法中调用了一个非静态方法

在我的控制器里,我刚刚移除了“静电”,它就像一个符咒一样工作。
谢谢大家的意见。

@Nkosi你说得对。我已经更新了我的问题,谢谢。编辑:我也在Startup.cs中添加了AlunoRepository,但错误仍然存在。@Nkosi事实上我的问题是在一个静态方法中试图调用一个非静态方法。我已经解决了。谢谢你的意见:)谢谢你的回答。我非常感谢,我知道,但错误与“等待”无关。错误是:当我尝试调用非静态字段、方法或属性时,需要对其进行对象引用。我不明白为什么,因为在DI和构造内部,我正在调用接口。@NunoAfonsoSilva-请参阅我的updateAwesome。感谢您指出这一点,但我的主要问题仍然存在。请您查看主这个问题的重点是什么?@NunoAfonsoSilva是的,如果你没有正确使用读卡器,你会得到空对象。你什么时候得到这个异常?如果你对DI有问题,异常会立即出现,在第一个屏幕之前。
public interface IAlunoRepository
    {
        public Task<IList<AlunoModel>> ObterAlunos();
    }
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;
        }
    }
 while (await reader.ReadAsync()) {
    for (int i = 0; i < reader.FieldCount; i++) {
         // Process each column as appropriate
          object obj = await reader.GetFieldValueAsync<object>(i);
        }
}

var resultList = await alunoService.ObterAlunos();

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