Just found this interesting article:
Heartysoft.com | Anonymous Types are Internal, C# 4.0 Dynamic Beware!That explained why my spark templates where failing at runtime because the default dynamic object only works for public and non-internal members.
I implemented the following class in order to use dynamic and non-dynamic models in our spark templates that are used in standalone mode for emailing templating:
public class DynamicViewData : DynamicObject
{
private readonly object _model;
public DynamicViewData(object model)
{
_model = model;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
var member = _model.GetType().GetMember(binder.Name,
BindingFlags.Instance |
BindingFlags.Public |
BindingFlags.NonPublic).FirstOrDefault();
if (member != null)
{
switch (member.MemberType)
{
case MemberTypes.Field:
result = ((FieldInfo)member).GetValue(_model);
return true;
case MemberTypes.Property:
result = ((PropertyInfo)member).GetValue(_model, null);
return true;
}
}
return base.TryGetMember(binder, out result);
}
}
And a custom AbstractSparkView which has a dynamic property where I'm passing an instance of this class together with the anonymous model.
Now I don't have to define in my spark templates the model type, and also I don't have to define in my code every single viewmodel.


0 comments:
Post a Comment