首页 > 解决方案 > ASP.NET Core 依赖注入:NullReferenceException 试图访问其接口中定义的具体类成员

问题描述

这变得很奇怪,因为我已经做了好几次了,没有任何问题。我正在使用 ASP.NET Core 3.1 作为记录。问题是我在 ConfigureServices Startup 方法中注册了一个具体类型及其相关接口:

public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<MyDbContext>(options =>
        options.UseSqlServer(
             Configuration.GetConnectionString("MyDatabase")
            ));

        ProfileManager.RegisterMappingService(services);

        services.AddScoped<IUserWorkerService, UserWorkerService>();

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
        services.AddControllers();

我在控制器中注入该依赖项:

[Route("api/[controller]")]
[ApiController]
public class UsersController : ControllerBase
{
    private readonly IUserWorkerService userWorkerService;

    public UsersController(IUserWorkerService userWorkerService)
    {
        this.userWorkerService = userWorkerService ?? throw new ArgumentNullException(nameof(userWorkerService));
    }

    [AllowAnonymous]
    [HttpPost("authenticate")]
    public IActionResult Authenticate(string userName, string password)
    {
        var user = this.userWorkerService.Authenticate(userName.Trim(), password.Trim());

        if (user == null)
            return Unauthorized();
        return Ok(System.Text.Json.JsonSerializer.Serialize(user));
    }
}

这是界面:

    public interface IUserWorkerService
{
    public UserDto Authenticate(string userName, string password);
}

这是具体的类:

public class UserWorkerService : IUserWorkerService
{
    private readonly MyDbContext dbContext;
    private readonly IMapper mapper;

    public UserWorkerService(MyDbContext dbContext, IMapper mapper)
    {
        this.dbContext = dbContext;
        this.mapper = mapper;
    }

    public UserDto Authenticate(string userName, string password)
    {
*blah blah*
    }
}

当我发出 POST 请求时,我正确地落在控制器的 ActionResult 上,但 UserWorkerService 实例不包含在其接口中定义的成员,只包含注入的成员 IMapper 和 MyDbContext。 在此处输入图像描述

因此,当代码到达 UsersController 中的 Authenticate 方法调用时,调试器会抛出 NullReferenceException。 在此处输入图像描述

我在这里想念什么?

标签: asp.net-coredependency-injectioncontrollerasp.net-core-webapi

解决方案


推荐阅读