我的视图模型如下
public VMTest
{
public int property1 {get;set;}
public int depdendentproperty
{
get
{
return IMyservice.GetData(property1);
}
}
}
我想通过依赖注入来调用Myservice
方法。但是为此,我需要为viewmodel添加一个看起来不太正确的重载构造函数。我的查询是如何从有无依赖注入的服务中获取viewmdel的属性值。一种解决方法是在服务中添加默认构造函数并直接调用服务方法。请建议
实际上,我的要求是通过get方法实现它。详细地说,我将对Property1应用RequiredIf属性。每当验证property1时,它取决于相关属性
您正在打破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);
}
在控制器作用域中,您可以访问HttpContext.RequestServices
属性,该属性表示HttpContext.RequestServices
上本机IoC
容器。