I'm upgrading a project from Glass Mapper v2 (Glass.Mapper.Sitecore) to v4 (Glass.Mapper.Sc) and I ran into an issue where our solution was using the InstanceContext object to get classes by template Id. I couldn't find that InstanceObject or a similar class in the new Glass Mapper. Here's a snippet of the 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);
}
In the "new" glass.mapper you can get the class by querying the TypeConfigurations
property of Glass' context object.
Something like this:
var configs = Glass.Mapper.Context.Default.TypeConfigurations.Select(x => x.Value as SitecoreTypeConfiguration);
var types = configs.Where(x => x.TemplateId == templateId);