使用依赖注入从服务获取视图模型属性

问题描述 投票:0回答:1

我的视图模型如下

public VMTest
{
  public int property1 {get;set;}
  public int depdendentproperty 
  {
    get 
    {
        return IMyservice.GetData(property1);
    }

  }
}

我想通过依赖注入来调用Myservice方法。但是为此,我需要为viewmodel添加一个看起来不太正确的重载构造函数。我的查询是如何从有无依赖注入的服务中获取viewmdel的属性值。一种解决方法是在服务中添加默认构造函数并直接调用服务方法。请建议

实际上,我的要求是通过get方法实现它。详细地说,我将对Property1应用RequiredIf属性。每当验证property1时,它取决于相关属性

c# .net asp.net-core asp.net-core-2.0
1个回答
0
投票

您正在打破ViewModel应该做什么的范式。您可以至少在返回Controller的服务中的MethodViewModel上进行准备。

添加名称空间:

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容器。

© www.soinside.com 2019 - 2024. All rights reserved.