【发布时间】: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