1

I have an extension method that takes in IHtmlHelper, like this :

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

This function is then called from a Razor page.

I have my settings loaded in my startup, and it's ready to access via dependency injection. How would I go about this, without creating a static settings class? Is it possible to do method injection here, without having to inject the settings from the page on every call?

WynDiesel
  • 1,104
  • 7
  • 38
  • 1
    You may resolve the dependency inside the method using IServiceProvider, [like this](https://stackoverflow.com/questions/50664743/net-core-resolve-dependency-manually-anywhere-in-the-code) – Nouman Jul 01 '20 at 14:41
  • 1
    Related: https://stackoverflow.com/questions/55213803/use-dependency-injection-in-static-class – Steven Jul 01 '20 at 20:13
  • 1
    Related: https://stackoverflow.com/questions/52325438/how-to-inject-dependency-to-static-class/52327577#52327577 – Steven Jul 01 '20 at 20:15

1 Answers1

1

Based on the static nature of the code being accessed, a service locator approach would need to be applied.

Resolve the desired type via the IHtmlHelper.ViewContext, which has access to the HttpContext. Allowing access to the IServiceProvider via the HttpContext.RequestServices

public static HtmlString HelpContext(this IHtmlHelper helper) {

    IServiceProvider services = helper.ViewContext.HttpContext.RequestServices;

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

    //...
    
}
Nkosi
  • 235,767
  • 35
  • 427
  • 472