首页 > 解决方案 > 使用依赖注入从服务获取视图模型属性

问题描述

我有如下视图模型

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

标签: c#.netasp.net-coreasp.net-core-2.0

解决方案


你打破了ViewModel应该做什么的范式。您至少可以ControllerMethod返回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上的本机IoC容器的属性。


推荐阅读