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
    将其注入服务,从而提供对控制器及其模型状态的引用:
  • 尽管得到了这个直接的答案,但这可能仍然不是一件明智的事情。本教程是我最初使用的:
  • 但它现在已经很老了,它从未兑现将服务与控制器完全解耦的承诺。实现我想要的更好的方法可能是遵循@Tseng提出的三种解决方案之一,如下所示:

    它非常有说服力地论证了为什么最好不要将服务层与ASP.NETMVC耦合,这样它就可以跨桌面和控制台应用程序(以及其他应用程序)使用

    这就是我现在要做的,而不是坚持使用微软教程


    我希望这能帮助其他人解决这个问题。

    请检查一条建议:不要为您提供服务嗨@Nayan,我读了这个链接,但我不明白它将如何解决问题。请您详细说明一下,或者我只是没有解释好吗?嗨@Xerilio,这个链接非常有趣,谢谢,非常有意义。我有有种感觉我可能做错了什么。我只是在遵循本教程:。我能感觉到它有点可笑(比如说它是解耦的,但从来没有完全解耦过)。你分享的曾先生的答案似乎更接近我应该做的。
    public class StudentService : IStudentService
    {
        private readonly ModelStateDictionary _modelState;
    
        public MyService(IActionContextAccessor actionContextAccessor)
        {
            _modelState = actionContextAccessor.Context.ModelState;
        }