nsh*_*ish 1 dependency-injection model-validation ivalidatableobject asp.net-core
我在我的 api 控制器类之一中使用以下 DTO 类,在一个 asp.net 核心应用程序中。
public class InviteNewUserDto: IValidatableObject
{
private readonly IClientRepository _clientRepository;
public InviteNewUserDto(IClientRepository clientRepository)
{
_clientRepository = clientRepository;
}
//...code omitted for brevity
}
Run Code Online (Sandbox Code Playgroud)
这就是我在控制器中使用它的方式
[HttpPost]
public async Task<IActionResult> RegisterUser([FromBody] InviteNewUserDto model)
{
if (!ModelState.IsValid) return BadRequest(ModelState);
//...omitted for brevity
}
Run Code Online (Sandbox Code Playgroud)
但是我System.NullReferenceException在 DTO 类中得到了一个这是因为依赖注入在 DTO 类中不起作用。我怎样才能解决这个问题 ?
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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1705 次 |
| 最近记录: |