我有如下的视图模型
public VMTest
{
[RequiredIf("depdendentproperty", "1")]
public int property1 {get;set;}
public int depdendentproperty
{
get
{
return IMyservice.GetData(property1);
}
}
}
我想通过依赖注入来调用Myservice
方法。但为此,我需要为viewmodel添加一个重载构造函数,这似乎不正确。我的问题是如何从带有或不带有依赖项注入的服务中获取viewmdel的属性值。一次性解决方案是在服务中添加默认构造函数并直接调用服务方法。请建议
实际上,我的要求是通过get方法来实现它。为了详细说明,我正在属性1上应用RequiredIf属性。无论何时验证属性1,它都取决于依赖属性
您正在打破ViewModel
应该做什么的范式。您至少可以在返回ViewModel
的服务中的Controller
或Method
上准备它。
添加命名空间:
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);
}
在控制器作用域中,您可以访问HttpContext.RequestServices
属性,该属性是asp.net-core上本地IoC
容器的表示。