Reputation: 3073
I have created extension methods for IUrlHelper.
public static class UrlHelperExtensions
{
public static string JavaScript(this IUrlHelper helper, string contentPath, IOptions<TypeScriptOptions> tsOptions)
{
if (tsOptions.Value != null && tsOptions.Value.Minify)
{
contentPath = Path.ChangeExtension(contentPath, ".min.js");
}
return helper.Content(contentPath);
}
public static string Css(this IUrlHelper helper, string contentPath, IOptions<LessOptions> lessOptions)
{
if (lessOptions.Value != null && lessOptions.Value.Minify)
{
contentPath = Path.ChangeExtension(contentPath, ".min.css");
}
return helper.Content(contentPath);
}
}
I would like to pass IOptions<TypeScriptOptions> tsOptions
and IOptions<LessOptions> lessOptions
to the methods using .NET Core's dependency injection.
In a Razor view I have the following:
@inject IOptions<CssOptions> lessOptions
<link href="@Url.Css("~/css/site.css", lessOptions)" rel="stylesheet" asp-append-version="true">
But I would simply like to do:
<link href="@Url.Css("~/css/site.css")" rel="stylesheet" asp-append-version="true">
I've tried looking at the .NET Core docs and I've done a few Google searches but I can't seem to find a way to achieve what I want without resorting to Tag Helpers which isn't something I want to do.
How can I get this to work?
Upvotes: 2
Views: 2873
Reputation: 6398
As @Romoku said, extension methods are static methods and only take state as argument (or from static state).
You either need to keep using the strategy you have, passing it as an argument. Or drop the idea of extension method and create some helper class or service that gets resolved via DI:
public class UrlHelperService
{
private IOptions<CssOptions> _cssOptions;
private IOptions<JavaScriptOptions> _jsOptions;
private IUrlHelper _urlHelper;
public UrlHelperService(
IOptions<CssOptions> cssOptions,
IOptions<JavaScriptOptions> jsOptions,
IUrlHelper urlHelper)
{
_cssOptions = cssOptions;
_jsOptions = jsOptions;
_urlHelper = urlHelper;
}
public string JavaScript(string contentPath)
{
if (_jsOptions.Value != null && _jsOptions.Value.Minify)
{
contentPath = Path.ChangeExtension(contentPath, ".min.js");
}
return _urlHelper.Content(contentPath);
}
public string Css(string contentPath)
{
if (_cssOptions.Value != null && _cssOptions.Value.Minify)
{
contentPath = Path.ChangeExtension(contentPath, ".min.css");
}
return _urlHelper.Content(contentPath);
}
}
The container needs this class registered, e.g:
services.AddScoped<UrlHelperService>()
Or whatever lifecycle this type should have.
And the service would be injected in your view instead of the options
instances:
@inject UrlHelperService urlHelperService
<link href="@urlHelperService.Css("~/css/site.css")" rel="stylesheet" asp-append-version="true">
Upvotes: 2