0

我的 ASP.NET Core 应用程序正在使用dotliquid。我正在创建自己的自定义 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 的模板代码,它存储ITagFactory在私有静态字段中

  private static Dictionary<string, Tuple<ITagFactory, Type>> Tags { get; set;}

就我而言,每个请求都有自己的IHttpContextAccessor,我不想为每个请求创建工厂

4

1 回答 1

0

我想我找到了。按照SO,我们可以注册 IHttpContextAccessor 单例。从 .NET Core 2.1 开始,添加了一个扩展方法来正确地将 an 注册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));
    }
于 2019-05-28T20:13:17.223 回答