RazorEngineCore - How to use extension methods

Viewed 245

I am working with RazorEngineCore and am coming across an issue where extension methods are not being identified properly. In my sample below, I am trying to use LINQ's single, and the error is:

'System.Collections.Generic.List' does not contain a definition for 'First'

I've added the required assemblies using AddAssemblyReferenceByName() and assume it would load correctly. Yet I'm still getting the error.

Sample code:

class Program
{
    static string Content = @"
        Hello @Model.Name

        First item: @Model.Items.First();

        @foreach(var item in @Model.Items)
        {
            <div>- @item</div>
        }

        <div data-name=""@Model.Name""></div>

        <area>
            @{ RecursionTest(3); }
        </area>

        @{
            void RecursionTest(int level){
                if (level <= 0)
                {
                    return;
                }
                    
                <div>LEVEL: @level</div>
                @{ RecursionTest(level - 1); }
            }
        }";

    static void Main(string[] args)
    {
        IRazorEngine razorEngine = new RazorEngine();
        IRazorEngineCompiledTemplate template = razorEngine.Compile(Content,
            builder =>
            {
                builder.AddAssemblyReferenceByName("System.Collections");
                builder.AddAssemblyReferenceByName("System.Linq");
            });

        string result = template.Run(new
        {
                Name = "Alexander",
                Items = new List<string>()
                {
                        "item 1",
                        "item 2"
                }
        });

        Console.WriteLine(result);
        Console.ReadKey();
    }
}

Edit: When I call the extension method fully qualified, it works. ie, calling System.Linq.First(myList) instead of myList.Single().

0 Answers
Related