C# 使用Depdency注入从服务获取视图模型属性TF
我有如下的模型C# 使用Depdency注入从服务获取视图模型属性TF,c#,.net,asp.net-core,asp.net-core-2.0,C#,.net,Asp.net Core,Asp.net Core 2.0,我有如下的模型 public VMTest { [RequiredIf("depdendentproperty", "1")] public int property1 {get;set;} public int depdendentproperty { get { return IMyservice.GetData(property1); } } } 我想通过依赖项注入调用Myservice方法。但为此,我需要为viewmod
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,它都取决于dependentproperty您正在打破
视图模型应该做什么的范式。您至少可以在控制器
或服务中返回视图模型
的方法上准备它
添加名称空间:
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);
}
public IActionResult GetData()
{
var service=this.HttpContext.RequestServices.GetService();
var property1Value=1;
var结果=新的VMTest()
{
property1=property1值,
DependentProperty=service.GetData(property1Value)
};
返回视图(结果);
}
在控制器作用域中,您可以访问属性,该属性是上的本机IoC
容器的表示。谢谢,我需要通过get方法实现它。我已经更新了question@Zia不建议通过get方法获取它。提供的答案在评估中是正确的。在将属性传递给操作之前,您可能需要创建一个模型绑定器来填充该属性。@Nkosi您知道如何从asp.net核心项目的任何作用域获取容器实例吗?@FelipeOriani如果使用自定义模型绑定器,则您可以通过这意味着您可以访问RequestServices。参考文献