【问题标题】:Method injection in extension method扩展方法中的方法注入
【发布时间】:2020-10-22 00:52:51
【问题描述】:

我有一个接受 IHtmlHelper 的扩展方法,像这样:

public static HtmlString HelpContext(this IHtmlHelper helper)
{
    return "";
}

然后从 Razor 页面调用此函数。

我在启动时加载了我的设置,并且可以通过依赖注入进行访问。如果不创建静态设置类,我将如何处理?是否可以在这里进行方法注入,而不必在每次调用时都从页面中注入设置?

【问题讨论】:

标签: c# asp.net-core dependency-injection configuration


【解决方案1】:

基于被访问代码的静态特性,需要应用服务定位器方法。

通过IHtmlHelper.ViewContext 解析所需的类型,它可以访问HttpContext。允许通过HttpContext.RequestServices访问IServiceProvider

public static HtmlString HelpContext(this IHtmlHelper helper) {

    IServiceProvider services = helper.ViewContext.HttpContext.RequestServices;

    var x = services.GetRequiredService<IMyType>();

    //...
    
}

【讨论】:

    猜你喜欢
    • 2017-11-02
    • 2011-06-29
    • 1970-01-01
    • 1970-01-01
    • 2016-02-13
    • 1970-01-01
    • 1970-01-01
    • 2015-03-12
    • 2014-05-13
    相关资源
    最近更新 更多