C#ASP.NET Web API依赖项注入将当前控制器的属性传递给服务类构造函数
假设我有一个控制器类,该类将服务类的一个实例作为其构造函数中的参数,该构造函数通过依赖项注入进行注入:C#ASP.NET Web API依赖项注入将当前控制器的属性传递给服务类构造函数,c#,dependency-injection,asp.net-core-webapi,C#,Dependency Injection,Asp.net Core Webapi,假设我有一个控制器类,该类将服务类的一个实例作为其构造函数中的参数,该构造函数通过依赖项注入进行注入: [ApiController] [Route("api/[controller]")] public class StudentsController : ControllerBase { private readonly IStudentsService _studentsService; public S
[ApiController]
[Route("api/[controller]")]
public class StudentsController : ControllerBase
{
private readonly IStudentsService _studentsService;
public StudentsController(IStudentsService studentsService)
{
_studentsService= studentsService;
}
假设注入的服务将Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary的实例作为构造函数中的参数,如下所示:
public class StudentsService : IStudentsService
{
private ModelStateDictionary _modelStateDictionary;
public StudentsService(ModelStateDictionary modelStateDictionary)
{
_modelStateDictionary = modelStateDictionary;
}
是否有一种方法可以确保注入StudentsService构造函数的ModelStateDictionary不仅仅是任何ModelStateDictionary,而是实例化StudentsService的特定StudentsController正在使用ModelStateDictionary?
即,与对我的API的当前请求关联的控制器
在启动
中,它可能看起来像这样:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddScoped<IStudentsService, StudentsService>(provider => provider.DoSomethingCleverToEnsureThisServiceGetsTheModelStateDictionaryOfItsController()
);
public void配置服务(IServiceCollection服务)
{
services.AddControllers();
services.AddScoped(provider=>provider.doSomethingLeverToEnsurethisServiceGetsModelStateDictionaryFitsController()
);
我希望这样做的原因是,我可以在服务层中对请求执行进一步的验证,并使用自己的ModelStateDictionary将验证错误传递回控制器。
谢谢你的建议!在阅读了@Xerilio提供的StackOverflow问题后,我学到了两件事:
IActionContextAccessor
接口
Microsoft.AspNetCore.Mvc.Infrastructure
将其注入服务,从而提供对控制器及其模型状态的引用:我希望这能帮助其他人解决这个问题。请检查一条建议:不要为您提供服务嗨@Nayan,我读了这个链接,但我不明白它将如何解决问题。请您详细说明一下,或者我只是没有解释好吗?嗨@Xerilio,这个链接非常有趣,谢谢,非常有意义。我有有种感觉我可能做错了什么。我只是在遵循本教程:。我能感觉到它有点可笑(比如说它是解耦的,但从来没有完全解耦过)。你分享的曾先生的答案似乎更接近我应该做的。
public class StudentService : IStudentService
{
private readonly ModelStateDictionary _modelState;
public MyService(IActionContextAccessor actionContextAccessor)
{
_modelState = actionContextAccessor.Context.ModelState;
}