Supposing I have a controller class that takes an instance of a service class as an argument in its constructor, which is injected via dependency injection:
[ApiController]
[Route("api/[controller]")]
public class StudentsController : ControllerBase
{
private readonly IStudentsService _studentsService;
public StudentsController(IStudentsService studentsService)
{
_studentsService= studentsService;
}
And supposing that the injected service takes an instance of Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary as an argument in the constructor, like this:
public class StudentsService : IStudentsService
{
private ModelStateDictionary _modelStateDictionary;
public StudentsService(ModelStateDictionary modelStateDictionary)
{
_modelStateDictionary = modelStateDictionary;
}
Is there a way that I can ensure that the ModelStateDictionary injected into the constructor of the StudentsService isn't just any ModelStateDictionary but is the ModelStateDictionary being used by the particular StudentsController that instantiated the StudentsService? I.e. the controller that is associated with the current request to my API?
Perhaps it might look something like this in Startup:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddScoped<IStudentsService, StudentsService>(provider => provider.DoSomethingCleverToEnsureThisServiceGetsTheModelStateDictionaryOfItsController()
);
The reason I wish to do this is so that I can perform further validation on the request in the service tier and pass validation errors back the controller using its own ModelStateDictionary. Thanks for any advice!