首页 > 解决方案 > 如何在子视图中使用剃刀布局视图中的注入服务

问题描述

刚刚了解在 asp.net core razor 视图中注入的服务。但是我还没有找到如何在子视图中使用在布局视图中注入的服务(将被许多视图使用)。

也许在概念上是这样的:

布局视图

@inject IOptions<PortalConfiguration> OptionsPortalConfiguration

<some HTLM markup>
@RenderBody(OptionsPortalConfiguration) <--pass it here???

子视图

Not sure how to reference it.

标签: c#asp.net-mvcrazordependency-injection

解决方案


这种情况的另一种方法是创建静态辅助方法,可以在所有视图中调用而无需注入。

public static class TestHelperExtensions
{
    public static ITestProvider TestProvider { get; set; }

    public static string Get(this ITestHelper html, string arg)
    {
        return TestProvider.Get(arg);
    }
}

推荐阅读