依赖注入到asp.net核心的视图模型类中

时间:2018-07-16 12:53:09

标签: asp.net-core dependency-injection model-validation ivalidatableobject

我在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类中不起作用。 我该如何解决?

2 个答案:

答案 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>();

   ...
}