我的ASP.NET Core应用程序正在使用dotliquid。我正在创建自己的自定义点液标记,并且想在自定义标记中注入IHttpContextAccessor
。根据我的研究,我必须创建ITagFactory
来创建标签并注入IHttpContextAccessor
。
我的自定义工厂
public class LiquidTagFactory : DotLiquid.ITagFactory
{
private readonly Type _tagType;
private readonly string _tagName;
private readonly IHttpContextAccessor _contextAccessor;
public string TagName { get { return _tagName; } }
public LiquidTagFactory(Type tagType, string tagName, IHttpContextAccessor contextAccessor)
{
_tagType = tagType;
_tagName = tagName;
_contextAccessor = contextAccessor;
}
public Tag Create()
{
return (Tag)Activator.CreateInstance(_tagType, _contextAccessor);
}
}
我的自定义标签
public class TextBox : DotLiquid.Tag
{
private string _html = null;
private readonly IHttpContextAccessor _contextAccessor;
public TextBox(IHttpContextAccessor contextAccessor)
{
_contextAccessor = contextAccessor;
}
public override void Initialize(string tagName, string markup, List<string> tokens)
{
// here i want to store some values into HttpContext.Items
_contextAccessor.HttpContext.Items.Add("key","somedata");
base.Initialize(tagName, markup, tokens);
}
public override void Render(Context context, TextWriter result)
{
_html = CreateHtml();
result.Write(_html);
base.Render(context, result);
}
}
那我将把这个工厂注册为
Template.RegisterTagFactory(new LiquidTagFactory(typeof(TexBox), "textbox", _httpContextAccessor));
但是,我正在使用ASP.NET Core。我不确定如何使用.NET Core的依赖项注入来注册自定义标签工厂?
查看dotliquid's template代码,它将ITagFactory
存储在私有静态字段中
private static Dictionary<string, Tuple<ITagFactory, Type>> Tags { get; set;}
就我而言,每个请求都有自己的IHttpContextAccessor
,我不想为每个请求创建工厂
答案 0 :(得分:0)
我想我找到了。根据{{3}},我们可以注册IHttpContextAccessor单例。
从.NET Core 2.1开始,已经添加了扩展方法,可以将IHttpContextAccessor
正确注册为单例。只需在您的ConfigureServices()方法中添加以下内容:
services.AddHttpContextAccessor();
这等效于:
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
,然后在启动时在Configure()方法中注册工厂。确保将IHttpContextAccessor
作为参数传递
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IOptions<DomainOptions> domainOps, IHttpContextAccessor httpContextAccessor)
{
Template.RegisterTagFactory(new LiquidTagFactory(typeof(TextBox), "textbox", httpContextAccessor));
}