asp.net-core - 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。
我在这里想念什么?
解决方案
推荐阅读
- tensorflow - 模型和权重不从检查点加载
- javascript - 不和谐.JS | 音乐机器人“错误:视频不可用”
- java - Java - 使用特定类型的接口
- git - 当超级项目处于分离头时更新 git 子模块
- java - 如何在没有任何导入的情况下打印在主类中分配的子类中的数组
- python - Linux - Pyinstaller 错误“无法执行脚本” - 将 Python 转换为 ELF 可执行文件
- javascript - 寻找更有效的方法来计算两个输入字段的值
- mysql - 即使没有对表进行任何更改,启动和提交 MySQL 事务是否有很大的成本?
- vue.js - 在字符串文字上使用带有切片的 v-if
- c++ - C++ 读取键盘事件