Closed Hugozys closed 3 years ago
You don’t need
@inherits RazorEngineCore.RazorEngineTemplateBase<TestModel>
@{
Model.Initialize();
}
In testpayload variable
Hi. Thanks for the reply. I get a little confused about this. This was me trying to reproduce the exception I met so it's a simplified version. The real template string is much more complicated but basically it will invoke member functions in the template at multiple places:
@inherits RazorEngineCore.RazorEngineTemplateBase<TestModel>
@{
Layout = "~/_layout.cshtml"
Model.Initialize();
}
<b>@Model.OtherMemberFunction()</b>
<b>@Model.Name</b>
// omit other code
Just wondering what are the correct format? Or it simply doesn't support these use cases? Maybe to let this minimum working example make more sense:
public class TestModel
{
public string Name {get; set;}
public string Age{get; set;}
public string PrintNameAge()
{
return $"{Name}-{Age}";
}
}
var testpayload = @"
@inherits RazorEngineCore.RazorEngineTemplateBase<TestModel>
<b>@Model.PrintNameAge()</b>
";
var engine = new RazorEngine();
var compiled = engine.Compile(testpayload, new Dictionary<string, string>());
var result = compiled.Run(new TestModel
{
Name = "John"
Age = 25
});
Apologize if I understand this incorrectly.
So it seems I need to override the TryInvokeMember
method in AnonymousTypeWrapper
to make this work.
If I override the TryInvokeMember to:
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
var methodInfo = this.model.GetType().GetMethods()?
.Where(m => (m.Name == binder.Name) && (binder.CallInfo.ArgumentCount == m.GetParameters()?.Count()))
.First(m =>
{
int ind = 0;
return m.GetParameters()?.Aggregate(true, (match, next) => match && next.ParameterType.IsAssignableFrom(args[ind++].GetType())) ?? true;
});
if (methodInfo == null)
{
return false;
}
result = methodInfo.Invoke(this.model, args);
return true;
}
I don't see that error any more.
Yes, AnonymousTypeWrapper does not implement functions calls (until you did it). I think this code should be added in next version.
However this code is looks odd to me:
@{
Model.Initialize();
}
The idea was to initialize model on compiled.Run
moment, not in the template. When template is being executed it is too late on initialize model.
I’ll implement same idea as you do in PR “in completely different way” not to make any concerns about it :)
closing issue for now
Target Framework is net48. Here's the
MWE
:Here's the exception I get when I run this
mwe
:Any idea where I did it wrong? If I just fall back to the basic usage, it also works: