Missing InstanceContext when upgrading from Glass.Mapper.Sitecore to Glass.Mapper.Sc
I am upgrading a project from Glass Mapper v2 (Glass.Mapper.Sitecore) to v4 (Glass.Mapper.Sc) and I ran into an issue where our solution used an InstanceContext object to get classes by template id. I couldn't find this InstanceObject or similar class in the new Glass Mapper. Here is a piece of code using it, hopefully it shows where I went wrong.
protected InstanceContext InstanceContext;
public MappingService(ISitecoreContext context)
{
InstanceContext = context.InstanceContext;
}
public T Map<T>(ISitecoreItem sourceItem) where T : class
{
Type sourceType = InstanceContext.GetClassById(sourceItem.TemplateId);
if (sourceType != null)
{
return Map(sourceItem, sourceType, typeof(T)) as T;
}
return Mapper.Map<T>(sourceItem);
}
// The GetClassById is implemented in an extensions class like this:
public static Type GetClassById(this InstanceContext context, Guid templateId)
{
if (context.ClassesById.ContainsKey(templateId))
{
SitecoreClassConfig config = context.ClassesById[templateId].FirstOrDefault();
if (config != null)
{
return config.Type;
}
}
return default(Type);
}
+3
source to share
1 answer
In the "new" glass .mapper, you can get the class by requesting the context TypeConfigurations
object of the Glass object.
Something like that:
var configs = Glass.Mapper.Context.Default.TypeConfigurations.Select(x => x.Value as SitecoreTypeConfiguration);
var types = configs.Where(x => x.TemplateId == templateId);
+2
source to share