尝试调用接口服务时抛出控制器错误 "An object Reference is required for the non-static field"
Controller Error "An object Reference is required for the non-static field" is being thrown when trying to call interface Service
我目前正在为我的网站构建一个 API 应用程序,以便在我的网站和数据库之间建立连接。
我还使用了一个 3 层架构(我有 1 个控制器,里面有来自 Azure Function 的 HttpTrigger,我有一个用于调用我的数据库查询的服务,我有一个存储库,我可以在其中进行查询数据库)。
所以这个结构是这样工作的:
控制器 (HttpTrigger) - 调用服务
服务调用存储库
存储库 - 执行对我的数据库的查询和 returns 要服务的值。
我正在尝试实现依赖注入的概念,我确实认为它在工作,因为我已经添加了一个 Startup.cs 文件来调用我的接口和 class实现我的界面。
问题是:在控制器上,我正在初始化我的接口,但是当我尝试从我的服务调用方法时,它抛出以下错误:“非静态字段需要对象引用, 方法或 属性 'AlunoController.alunoService'"
这些是我的文件:
IAlunoService - 接口
public interface IAlunoService
{
public Task<IList<AlunoModel>> ObterAlunos();
}
AlunoService - 实现接口方法
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 文件
[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 - 这就是我遇到问题的地方
#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;
}
}
我正在努力理解为什么这不起作用,因为我在我的 Controller Constructor 上调用了接口。虽然没用。
奇怪的是,我使用相同的“方式”来调用和实现服务文件上的接口,例如,我可以毫无问题地调用“alunoRepository”。
你能帮我解决这个问题吗?
我目前正在上大学,这与我的期末项目之一有关。
编辑:错误的屏幕截图:
如果您没有正确使用 reader,您将得到空对象。您必须以这种方式使用异步 reader:
while (await reader.ReadAsync()) {
for (int i = 0; i < reader.FieldCount; i++) {
// Process each column as appropriate
object obj = await reader.GetFieldValueAsync<object>(i);
}
}
而且因为你到处都在使用异步方法,所以你必须调用 Alunos_ObterLista.ObterAlunos as async:
var resultList = await alunoService.ObterAlunos();
.....
return new OkObjectResult(resultList );
我想出了问题所在。
一整天都在看它,却没有意识到我是在静态方法中调用非静态方法。
在我的控制器中,我刚刚删除了“静态”,它就像一个魅力。
感谢大家的意见。
我目前正在为我的网站构建一个 API 应用程序,以便在我的网站和数据库之间建立连接。 我还使用了一个 3 层架构(我有 1 个控制器,里面有来自 Azure Function 的 HttpTrigger,我有一个用于调用我的数据库查询的服务,我有一个存储库,我可以在其中进行查询数据库)。
所以这个结构是这样工作的: 控制器 (HttpTrigger) - 调用服务 服务调用存储库 存储库 - 执行对我的数据库的查询和 returns 要服务的值。
我正在尝试实现依赖注入的概念,我确实认为它在工作,因为我已经添加了一个 Startup.cs 文件来调用我的接口和 class实现我的界面。
问题是:在控制器上,我正在初始化我的接口,但是当我尝试从我的服务调用方法时,它抛出以下错误:“非静态字段需要对象引用, 方法或 属性 'AlunoController.alunoService'"
这些是我的文件:
IAlunoService - 接口
public interface IAlunoService
{
public Task<IList<AlunoModel>> ObterAlunos();
}
AlunoService - 实现接口方法
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 文件
[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 - 这就是我遇到问题的地方
#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;
}
}
我正在努力理解为什么这不起作用,因为我在我的 Controller Constructor 上调用了接口。虽然没用。
奇怪的是,我使用相同的“方式”来调用和实现服务文件上的接口,例如,我可以毫无问题地调用“alunoRepository”。
你能帮我解决这个问题吗? 我目前正在上大学,这与我的期末项目之一有关。
编辑:错误的屏幕截图:
如果您没有正确使用 reader,您将得到空对象。您必须以这种方式使用异步 reader:
while (await reader.ReadAsync()) {
for (int i = 0; i < reader.FieldCount; i++) {
// Process each column as appropriate
object obj = await reader.GetFieldValueAsync<object>(i);
}
}
而且因为你到处都在使用异步方法,所以你必须调用 Alunos_ObterLista.ObterAlunos as async:
var resultList = await alunoService.ObterAlunos();
.....
return new OkObjectResult(resultList );
我想出了问题所在。 一整天都在看它,却没有意识到我是在静态方法中调用非静态方法。
在我的控制器中,我刚刚删除了“静态”,它就像一个魅力。 感谢大家的意见。