为什么我得到 System.NullReferenceException: 对象引用未设置到对象的实例

Why im getting System.NullReferenceException: Object reference not set to an instance of an object

谁能给我解释一下这个异常?我在用户控制器中有这个方法

[HttpGet("{username}/plays")]
public async Task<ActionResult<int>> GetUserPlays(string username)
{
    return Ok(await _unitOfWork.TrackRepository.CountPlays(username));
} 

并且没有进入 TrackRepository 方法,它抛出异常:

2022-05-31 14:37:02.8644|0|ERROR|gspark.Middleware.ExceptionMiddleware|Object reference not set to an instance of an object. System.NullReferenceException: Object reference not set to an instance of an object.
   at gspark.Controllers.UsersController.GetUserPlays(String username) in C:\Users\GSpark\source\repos\gspark\gspark\Controllers\UsersController.cs:line 119
   at lambda_method202(Closure , Object )
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.Invoke(HttpContext context)

TrackRepository 方法:

public async Task<int> CountPlays(string username)
{
    return await _context.Tracks
       .Include(t => t.User)
       .Where(t => t.User.UserName == username)
       .SumAsync(t => t.Plays);
}

是关于映射的吗?或者如果它是导致问题的存储库方法,如果是这样,为什么调试不进入这个方法?抛出此异常的位置和原因?

如果您没有达到 CountPlays,则表明 _unitOfWorkTrackRepositorynull

为了澄清这一点,放置一个断点并检查调试器中的值。或者,如果您不能这样做,那么我会推荐一个类似于以下的 if 语句:

if (_unitOfWork == null || _unitOfWork.TrackRepository == null) 
{
    return new Exception("Ooops");
}

如果还不开心,那就分享初始化_unitOfWork对象的代码