1

我在我的一个 api 控制器类中使用以下 DTO 类,在一个 asp.net 核心应用程序中。

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

}

但是我System.NullReferenceException在 DTO 类中得到了一个 发生这种情况是因为依赖注入在 DTO 类中不起作用。我怎样才能解决这个问题 ?

4

2 回答 2

6

DI不会解决ViewModel.

你可以试试方法 validationContext.GetServiceValidate

public class InviteNewUserDto: IValidatableObject
{
    public string Name { get; set; }
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        IClientRepository repository = (IClientRepository)validationContext.GetService(typeof(IClientRepository));

        return null;
    }
}
于 2018-07-17T05:54:51.440 回答
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>();

   ...
}
于 2018-07-16T15:46:34.143 回答