How to write HtmlHelper in Fluent syntax

两盒软妹~` 提交于 2019-12-03 09:15:11

You have to define a builder interface and implementation. I hope my example can provide some guidance:

public static class MyHtmlExtensions
{
    public static IMyTagBuilder Tag(this HtmlHelper helper, string tag)
    {
        return new MyTagBuilder(tag);
    }
}

Then you define your builder interface and implementation:

public interface IMyTagBuilder : IHtmlString
{
    IHtmlString Content(string content);
}

public class MyTagBuilder : IMyTagBuilder
{
    private readonly TagBuilder _tagBuilder;

    public MyTagBuilder(string tag)
    {
        _tagBuilder = new TagBuilder(tag);
    }

    public IHtmlString Content(string content)
    {
        _tagBuilder.InnerHtml = content;
        return this;
    }

    public string ToHtmlString()
    {
        return _tagBuilder.ToString(TagRenderMode.NormalTag);
    }
}

Since IMyTagBuilder implements IHtmlString, it can be used either with or without calling .Content() afterwards.

A great trick to use when implementing fluent interfaces it to use a IFluentInterface to hide object members (ToString, Equals, GetHashCode and GetType) from IntelliSense, it removes some noise.

EDIT: A great resource for building fluent APIs is Daniel Cazzulino's screencast from building Funq here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!