WynDiesel
WynDiesel

Reputation: 1214

Method injection in extension method

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?

Upvotes: 1

Views: 1724

Answers (1)

Nkosi
Nkosi

Reputation: 247088

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>();

    //...
    
}

Upvotes: 1

Related Questions