1

I am using the following DTO class in one of my api controller class, in an asp.net core application.

public class InviteNewUserDto: IValidatableObject
{
  private readonly IClientRepository _clientRepository;

  public InviteNewUserDto(IClientRepository clientRepository)
  {
    _clientRepository = clientRepository;
  }

  //...code omitted for brevity
}

This is how I using it in a controller

[HttpPost]
public async Task<IActionResult> RegisterUser([FromBody] InviteNewUserDto  model)
{
  if (!ModelState.IsValid) return BadRequest(ModelState);

  //...omitted for brevity

}

But I am getting a System.NullReferenceException in the DTO class This is happening since dependency injection is not working in the DTO class. How can I fix this ?

nshathish
  • 417
  • 8
  • 23

2 Answers2

6

DI will not resolve dependences for ViewModel.

You could try validationContext.GetService in Validate method.

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

        return null;
    }
}
Edward
  • 28,296
  • 11
  • 76
  • 121
  • Thanks. It works. I made a small adjustment to code: `var repository = validationContext.GetService();`; I was looking at IModelBinder solutions, but this is clever and simple way. – nshathish Jul 17 '18 at 11:26
0

Did you register ClientRepository in startup.cs?

public void ConfigureServices(IServiceCollection services)
{
   ...
   // asp.net DI needs to know what to inject in place of IClientRepository
   services.AddScoped<IClientRepository, ClientRepository>();

   ...
}
Brad
  • 323
  • 2
  • 13