【问题标题】:Get View Model property tfrom service using depdendency injection使用依赖注入从服务中获取 Viewmodel 属性
【发布时间】:2020-02-28 09:37:07
【问题描述】:

我的视图模型如下

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# .net asp.net-core asp.net-core-2.0


    【解决方案1】:

    你打破了ViewModel 应该做什么的范式。您至少可以在返回ViewModel 的服务中的ControllerMethod 上准备它。

    添加命名空间:

    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 容器的表示。

    【讨论】:

    • 谢谢 我需要通过get方法实现。我已经更新了问题
    • @Zia 不建议通过 get 方法获取它。提供的答案在其评估中是正确的 您可能需要创建一个模型绑定器来填充属性,然后再将其传递给操作。
    • @Nkosi 你知道如何从 asp.net 核心项目的任何范围获取容器实例吗?
    • @FelipeOriani 如果使用自定义模型绑定器路由,那么您将可以通过ModelBindingContext 访问 HttpContext,这意味着您可以访问 RequestServices。参考Custom Model Binding in ASP.NET Core
    猜你喜欢
    • 1970-01-01
    • 2013-09-17
    • 1970-01-01
    • 2015-03-19
    • 2015-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多