c# - 使用依赖注入从服务获取视图模型属性
问题描述
我有如下视图模型
public VMTest
{
[RequiredIf("depdendentproperty", "1")]
public int property1 {get;set;}
public int depdendentproperty
{
get
{
return IMyservice.GetData(property1);
}
}
}
我想Myservice
通过依赖注入调用方法。但为此我需要为看起来不正确的视图模型添加一个重载的构造函数。我的查询是如何在有或没有依赖注入的情况下从服务中获取 viewmdel 的属性值。曾经的解决方案是在服务中添加默认构造函数并直接调用服务方法。请建议
其实我的要求是通过get方法来实现。为了详细说明,我在 property1 上应用了 RequiredIf 属性。无论何时验证 property1,它都取决于dependentproperty
解决方案
你打破了ViewModel
应该做什么的范式。您至少可以Controller
在Method
返回ViewModel
.
添加命名空间:
using Microsoft.Extensions.DependencyInjection;
并尝试类似以下操作方法示例:
public IActionResult GetData()
{
var service = this.HttpContext.RequestServices.GetService<IMyservice>();
var property1Value = 1;
var result = new VMTest()
{
property1 = property1Value ,
dependentyProperty = service.GetData(property1Value )
};
return View(result);
}
在控制器范围内,您可以访问表示asp.net-coreHttpContext.RequestServices
上的本机IoC
容器的属性。
推荐阅读
- javascript - 如何从 API 声明数组来代替硬编码数组?
- c# - 在默认浏览器的控制台应用程序中打开链接
- javascript - const { access_token } 和 const access_token 有什么区别?
- html - 如何在 HTML 的 src URL 中添加时间戳
- javascript - 为笔记应用程序动态创建模态
- c - 如何使用方法的结构参数分配给 C 中的另一个结构?
- c# - 是否可以引用 InputActionAsset 控件,即使在非活动状态下,也可以在 MonoBehavior 更新方法中使用?
- flutter - 使用 Flutter Hooks 库,当我尝试在 useEffect 中使用导航器时遇到了种族冲突
- python - 连接池的新手
- javascript - 页面上的数据与控制台中的数据不同