我在asp.net核心应用程序的一个api控制器类中使用以下DTO类。
public class InviteNewUserDto: IValidatableObject
{
private readonly IClientRepository _clientRepository;
public InviteNewUserDto(IClientRepository clientRepository)
{
_clientRepository = clientRepository;
}
//...code omitted for brevity
}
这就是我在控制器中使用它的方式
[HttpPost]
public async Task<IActionResult> RegisterUser([FromBody] InviteNewUserDto model)
{
if (!ModelState.IsValid) return BadRequest(ModelState);
//...omitted for brevity
}
但是我在DTO课程中得到了System.NullReferenceException
这是因为依赖注入在DTO类中不起作用。
我该如何解决?
答案 0 :(得分:3)
DI
不会解决ViewModel
的依赖关系。
您可以尝试使用validationContext.GetService
方法中的Validate
。
public class InviteNewUserDto: IValidatableObject
{
public string Name { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
IClientRepository repository = (IClientRepository)validationContext.GetService(typeof(IClientRepository));
return null;
}
}
答案 1 :(得分:0)
您是否在startup.cs中注册了ClientRepository?
public void ConfigureServices(IServiceCollection services)
{
...
// asp.net DI needs to know what to inject in place of IClientRepository
services.AddScoped<IClientRepository, ClientRepository>();
...
}