【问题标题】:Dependency Injection with ModelState使用 ModelState 进行依赖注入
【发布时间】:2019-11-21 13:09:39
【问题描述】:

首先,我知道在服务中使用 ModelState 通常是不受欢迎的,因为它将服务与 Mvc 框架紧密耦合。在我们的例子中,这不是问题,但我最终确实计划迁移到 IValidationDictionary 和 ModelState 包装器,但现在需要这一步。

现在,谈谈这个问题,这个很酷的人就在这里:

public class BaseService : IBaseService
    {

      protected MIRTContext _context;
      protected IMapper _mapper;
      //TODO: This tightly couples .NET MVC to our services. 
      // Could be imporoved with an interface and a ModelState wrapper
      // in order to decouple.
      private ModelStateDictionary _modelState;

      public BaseService(
        MIRTContext context, 
        IMapper mapper,
        ModelStateDictionary modelState
      ) {
        _context = context;
        _mapper = mapper;
        _modelState = modelState;
      }

     async Task<bool> IBaseService.SaveContext() {
        if(_modelState.IsValid) {
          try {
            await _context.SaveChangesAsync();
            return true;
          }
          catch {
            return false;
          }
        }
        else {
          return false;
        }
      }
    }

它一直给我这个错误:

尝试激活时无法解析“Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary”类型的服务

我假设我在 Startup.cs 的 ConfigureServices 中缺少某种 AddSingleton 东西,但我似乎无法弄清楚是什么。有谁知道如何让它正确地进行依赖注入?

【问题讨论】:

    标签: c# asp.net-core dependency-injection modelstate


    【解决方案1】:

    ModelState 不能通过依赖注入获得,但您可以使用IActionContextAccessor,它提供对当前ActionContext ModelState 属性的访问。

    首先,您需要为 DI 注册IActionContextAccessor

    services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
    

    接下来,更新您的 BaseService 类以使用它:

    public class BaseService : IBaseService
    {
        // ...
    
        private readonly IActionContextAccessor _actionContextAccessor;
    
        public BaseService(
            // ...
            IActionContextAccessor actionContextAccessor
        ) {
            // ...
            _actionContextAccessor = actionContextAccessor;
        }
    
        async Task<bool> IBaseService.SaveContext() {
            var actionContext = _actionContextAccessor.ActionContext;
    
            if (actionContext.ModelState.IsValid) {
                // ...
            }
            else {
                return false;
            }
        }
    }
    

    请注意,如果对 SaveContext 的调用在 MVC 及其控制器、过滤器等之外,则上面的 actionContext 将是 null

    【讨论】:

      猜你喜欢
      • 2015-09-26
      • 2014-01-19
      • 2014-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多