2
votes

In Sitecore, I Have 2 classes representing 2 possible nodes that can live as children of another node. My model contains a Children property which is an IEnumerable<INode> (INode being implemented by both classes). At runtime, I get the underlying type of each child to identify them and do some stuff. Everything works like a charm in my tests. But the actual implementation doesn't.

Basically in a razor view (inheriting from GlassView, I cycle through the collection of INode children and call .GetType() to identify the underlying class. But instead of getting the correct type, I get IColumnProxy type, which is the dynamic proxy glass mapper uses to create the view model.

Is there a way to get the actual type instead of the dynamic proxy? Thanks

EDIT: here is code example:

public interface INode {}

[SitecoreType(TemplateId = "AAAAAAAAA", AutoMap = true)]
public Class NodeType1 : INode
{
   public string PropertyA { get; set; }
}

[SitecoreType(TemplateId = "BBBBBBB", AutoMap = true)]
public Class NodeType2 : INode
{
   public string PropertyB { get; set; }
}

[SitecoreType(TemplateId = "CCCCCCC", AutoMap = true)]
public class SitecoreItem 
{
   [SitecoreChildren(InferType=true)]
   public virtual IEnumerable<INode> Nodes { get; set; }
}

And in the razor view:

@foreach(var node in item.Nodes)
{
  var type = node.GetType(); //INodeProxy
  var isNode1 = node is NodeType1; //False
  var isNode2 = node is NodeType2; //False
  var baseType = node.GetType().BaseType; //DynamicProxy
}

References in projects are Glass.Mapper and Glass.Mapper.Sc

EDIT: Update 1

Well, after digging a bit into it, it seems GlassMapper does it the way I am supposed to, but for some reason it doesn't work in my specific case. What Am I missing? References?

1
Instead of calling GetType() did you try if (node is MyType) ? glass.lu/Mapper/Sc/Tutorials/Tutorial17jammykam
Yes, I did, but it doesn't work as the interface implementation is somehow being hidden by the proxyHellraiser
Yep. that's what GlassMapper does - it generates its own interface implementations via Castle Windsor.Dmytro Shevchenko
Instead of checking for the concrete type, I would suggest that you check whether each object implements a certain interface - provided that the child items have 2 different Sitecore templates.Dmytro Shevchenko

1 Answers

2
votes

Well, after days of digging into this issue, I can affirm the answer is: not n this case. Basically, it SHOULD work. But in my case, there is no way to obtain the actual implementation of the interface. GlassMapper replaces the actual classes with the dynamic proxy implementation of the interface declared in the "children" property, so there is no way to cast each child to their actual types.

This is so bad, as prevents a whole bunch of dynamic scenarios from being implemented. I have created a custom mapper to handle this. But as I wrote before, it doesn't work in this specific case ONLY. Normally it should work.