Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HtmlHelper in .NET Core 2.0 with appsettings being injected in

I may be on a dead-end path, so I'm hoping that someone can either tell me to "turn around!" or "keep going!" - I'm attempting to convert an HTML helper from an ASP.NET 5 app into a .NET Core 2.0 app. I ran into trouble when calling the helper in an extension class. First, I read that .NET Core uses DI for getting appsettings into separate classes, so I set up the extension class with DI:

private readonly AppSettings _appsettings;

public HtmlHelperExtensions2(IOptions<AppSettings> appSettings)
{
    _appsettings = appSettings.Value;
}

And I'm able to return items from appSettings.json. The problem is that to use DI I needed to remove the "static" references from the class signature, so I also had to remove the "this" reference from the helper call:

public void HelpPanel(HtmlHelper htmlHelper, string thingId, string language)
{ }

Otherwise I get a compile error. But without the "this" reference the call expects a new HtmlHelper.

So I'm trying to get past this, if I can in fact get past it. Is this the right path or am I on a dead-end road here? Do I need to use something else in Core besides HtmlHelpers? I can't determine if they're even supported in Core.

like image 233
ewomack Avatar asked Oct 31 '25 03:10

ewomack


1 Answers

You can access the request's IServiceProvider from an instance of HtmlHelper and use the Service Locator anti-pattern to resolve instances from the DI container. Brace yourself for an example (it's a bit of a "train wreck"):

var appSettings = htmlHelper.ViewContext.HttpContext.RequestServices
    .GetRequiredService<IOptions<AppSettings>>()
    .Value;

Disclaimer: Statics and the Service Locator pattern are a little contentious. Tag Helpers don't use statics and support Dependency Injection, so you might want to consider switching to one of these if/when the time is right.

like image 195
Kirk Larkin Avatar answered Nov 02 '25 18:11

Kirk Larkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!