gpt4 book ai didi

c# - 在扩展方法中使用 .net 核心依赖项

转载 作者:行者123 更新时间:2023-11-30 23:08:10 26 4
gpt4 key购买 nike

我已经为 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);
}
}

我想通过 IOptions<TypeScriptOptions> tsOptionsIOptions<LessOptions> lessOptions到使用 .NET Core 依赖注入(inject)的方法。

在 Razor View 中,我有以下内容:

@inject IOptions<CssOptions> lessOptions
<link href="@Url.Css("~/css/site.css", lessOptions)" rel="stylesheet" asp-append-version="true">

但我只想做:

<link href="@Url.Css("~/css/site.css")" rel="stylesheet" asp-append-version="true">

我已经尝试查看 .NET Core 文档并进行了一些 Google 搜索,但我似乎无法找到一种方法来实现我想要的而不求助于 Tag Helpers,这不是我想要的做。

我怎样才能让它工作?

最佳答案

正如@Romoku 所说,扩展方法是静态方法,仅将状态作为参数(或来自静态)。

您要么需要继续使用已有的策略,将其作为参数传递。或者放弃扩展方法的想法并创建一些通过 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);
}
}

容器需要注册这个类,例如:

services.AddScoped<UrlHelperService>()或者这种类型应该具有的任何生命周期。

并且该服务将被注入(inject)到您的 View 中,而不是 options实例:

@inject UrlHelperService urlHelperService 
<link href="@urlHelperService.Css("~/css/site.css")" rel="stylesheet" asp-append-version="true">

关于c# - 在扩展方法中使用 .net 核心依赖项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46711046/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com