Request

Response

    Load design instances into a host application

    An exchange that uses design instancing stores each shared design once and gives every occurrence a reference to it. When you load that exchange, your connector rebuilds those relationships using whatever reusable-definition concept your host application already has: a block, a family, or a sub-assembly.

    This tutorial builds a loader that reads an exchange containing nested, shared designs and realizes it in a host application without duplicating geometry. You write four small operations against your application, and the loader handles the traversal, the sharing, and the transforms.

    Authoring the same structure is covered in Working with design instancing. Reading is the harder direction, because you recover a structure you didn’t choose.

    Before you begin

    You need:

    • An exchange whose elements carry designs. The Working with design instancing tutorial authors one.
    • A loaded ElementDataModel. Retrieve Data Exchanges covers fetching exchange data and creating the model:

      var exchangeData = await client.GetExchangeDataAsync(exchangeIdentifier);
      var model = ElementDataModel.Create(client, exchangeData);
      
    • A host application that can create a reusable definition, place occurrences of it, and nest one definition inside another. If yours can’t, you can still use the loader by treating every definition as geometry and baking the transforms yourself, but you lose the sharing.

    The model you load

    This tutorial uses the exchange authored in the previous tutorial: three chairs that share one Chair design, which itself contains four legs that share one Leg design.

    root
    ├── chair-001 "Chair 1" --> Chair design
    ├── chair-002 "Chair 2" --> Chair design
    └── chair-003 "Chair 3" --> Chair design
    
    Chair design
    ├── seat geometry
    ├── chair-leg-1 "Leg 1" at (0.0, 0.0, 0) --> Leg design
    ├── chair-leg-2 "Leg 2" at (0.4, 0.0, 0) --> Leg design
    ├── chair-leg-3 "Leg 3" at (0.0, 0.4, 0) --> Leg design
    └── chair-leg-4 "Leg 4" at (0.4, 0.4, 0) --> Leg design
    
    Leg design
    └── leg geometry
    
    Show More

    The legs live inside the shared Chair design rather than inside any individual chair, so all three chairs resolve to the same four leg elements. Twelve legs appear in the loaded model, and four elements exist in the exchange. A loader that misses this draws twelve.

    How the loader works

    Three rules cover the whole algorithm:

    1. Anything with content below it becomes a host definition — whether it’s a shared design reference or an element that simply has children. A leaf that carries only its own geometry is drawn directly.
    2. Build each definition once, then refer to it. A set of the design keys you’ve already built is the only bookkeeping you need.
    3. Never walk into a definition’s children from the outside. Those children are realized inside that definition, so placing them again draws them twice.

    Rule 1 is what keeps the outer walk free of recursion: a definition owns its whole subtree, so the walk never has to descend.

    The model exposes its elements as two lists, and the loader uses both for different jobs:

    ListContainsThe loader uses it to
    TopLevelElements The root's direct children — the three chairs Drive placement
    Elements Every element, flattened — the three chairs and the four legs Download geometry in one batch

    Caution: Don’t drive placement from Elements. It’s flattened, so it hands you the four legs as separate top-level entries even though they live inside the Chair design. You’d place three complete chairs plus four loose legs at the positions they occupy inside the chair design. Equally, don’t hand TopLevelElements to the geometry download: it processes only the elements you pass it and doesn’t descend into their children, so every nested element would come back empty.

    Step 1: Define the operations your host provides

    Your host application needs four operations. Everything else is SDK.

    public interface IHostDocument
    {
        // Converts one SDK geometry into your host's native geometry.
        object ConvertGeometry(IElementGeometry geometry);
    
        // Creates a reusable definition - a block, family, or sub-assembly - and registers it
        // under designKey. Members are positioned relative to the definition's origin.
        void CreateDefinition(string designKey, string displayName, IReadOnlyList<DefinitionMember> members);
    
        // Places one occurrence of the definition registered under designKey.
        void PlaceInstance(string designKey, Matrix4d placement, string name);
    
        // Draws standalone geometry that belongs to no shared design.
        void DrawGeometry(object geometry, Matrix4d placement, string name);
    }
    
    Show More

    A definition holds members, and there are exactly two kinds. The type is the discriminator, so your host switches on it instead of testing which field happens to be set:

    public abstract class DefinitionMember
    {
        // Always a single transform, relative to the containing definition's origin.
        public Matrix4d Placement { get; set; }
    
        // The element this member came from, for attribution. Null for a design's own geometry,
        // which belongs to the design rather than to any element inside it.
        public IElement SourceElement { get; set; }
    }
    
    // Geometry to draw inside the definition.
    public sealed class GeometryMember : DefinitionMember
    {
        public object Geometry { get; set; }
    }
    
    // A reference to another definition, nested inside this one.
    public sealed class NestedDefinitionMember : DefinitionMember
    {
        public string DesignKey { get; set; }
    }
    
    Show More

    IHostDocument and the member types are code you write, not SDK types. Adapt the names to your connector.

    Two things to handle in your host layer rather than in the loader:

    • Native handles. Hosts mint their own identifiers when you create a definition. Keep a map from designKey to native handle in your implementation and resolve PlaceInstance and nested members through it. The loader never sees a native handle.
    • Name collisions. Treat displayName as a label, not a key. Two designs can legitimately share one, so if your host requires unique definition names, disambiguate using the key.

    Step 2: Download the geometry in one batch

    GetElementGeometriesAsync takes the flattened element list and fetches each distinct geometry once, even when several elements resolve to the same one. Pass Elements, not TopLevelElements.

    // Element unique id to its downloaded geometry.
    private Dictionary<string, IReadOnlyList<IElementGeometry>> _geometry;
    
    private async Task DownloadGeometryAsync(CancellationToken cancellationToken)
    {
        var downloaded = await _model
            .GetElementGeometriesAsync(_model.Elements, cancellationToken)
            .ConfigureAwait(false);
    
        // Re-key by unique id. Assign through the indexer rather than calling ToDictionary: an
        // element can appear more than once in a list you assembled yourself, and ToDictionary
        // throws on a repeated key.
        _geometry = new Dictionary<string, IReadOnlyList<IElementGeometry>>(StringComparer.Ordinal);
    
        foreach (var pair in downloaded)
        {
            if (pair.Value != null)
            {
                _geometry[pair.Key.UniqueId] = pair.Value.ToList();
            }
        }
    }
    
    private IReadOnlyList<IElementGeometry> GeometryOf(IElement element)
        => _geometry.TryGetValue(element.UniqueId, out var geometry)
            ? geometry
            : Array.Empty<IElementGeometry>();
    
    Show More

    Re-keying by UniqueId here is a convenience, not a requirement. Each traversal of the model creates new wrapper objects over the same underlying asset, so the element you take from TopLevelElements and the same element reached through Elements are different instances — but they compare equal. IElement, IDesign, and IElementGeometry compare on their identifier, so you can use an element straight from one traversal to look up an entry the download keyed with an element from another.

    Caution: Equality on these types is exposed through Equals and GetHashCode, not through ==. Dictionaries, HashSet, List.Contains, and Distinct all use Equals and behave as you would expect. A hand-written element1 == element2 still compares references and is false for two wrappers over the same asset, so compare with Equals instead.

    Step 3: Place each top-level element

    The outer walk visits the root’s direct children and, for each, either places a definition or draws a leaf. There’s no recursion, because a definition owns its subtree.

    public async Task LoadAsync(CancellationToken cancellationToken)
    {
        await DownloadGeometryAsync(cancellationToken).ConfigureAwait(false);
    
        foreach (var element in _model.TopLevelElements)
        {
            Place(element);
        }
    }
    
    private void Place(IElement element)
    {
        var key = DefinitionKeyOf(element);
    
        if (key != null)
        {
            EnsureDefinition(key, element);
    
            // The placement is what separates the three chairs. Their definitions are identical;
            // the instance transform is the only difference, and the SDK doesn't apply it for you.
            _host.PlaceInstance(key, PlacementOf(element), element.Name);
            return;
        }
    
        foreach (var geometry in GeometryOf(element))
        {
            _host.DrawGeometry(_host.ConvertGeometry(geometry), PlacementOf(element), element.Name);
        }
    }
    
    Show More

    DefinitionKeyOf decides whether an element needs a definition at all, and under which key:

    private static string DefinitionKeyOf(IElement element)
    {
        // A shared design reference, keyed by the design so that every occurrence resolves to
        // the same host definition.
        if (element.Design?.IsDesignReference == true)
        {
            return element.Design.UniqueId;
        }
    
        // An element that isn't a design reference but has children still needs a definition for
        // the host to nest. It isn't shared, so key it by the element itself.
        if (element.GetChildElements().Any())
        {
            return element.UniqueId;
        }
    
        // A leaf: draw its geometry where it sits.
        return null;
    }
    
    private static Matrix4d PlacementOf(IElement element)
        => element.Transformation?.Matrix ?? new Matrix4d();
    
    Show More

    Two details in that method are worth knowing.

    Design is never null, so a null check tells you nothing about whether an element carries a design. IsDesignReference is the reliable test, and it returns true or null and never false, because a design with a single occurrence is indistinguishable from a one-off geometry holder. Compare against true rather than treating the value as a plain bool.

    The loader treats null as “not shared” and keys that definition by the element instead. That’s safe: a design nothing else points at has no sharing to preserve. It also avoids reading Design.UniqueId on an element that carries no design, which throws.

    Step 4: Build each definition once

    The first occurrence of a design builds its definition; every later occurrence skips straight to placing it. Nested designs are built before the parent that references them.

    // The design keys whose definitions already exist in the host.
    private readonly HashSet<string> _built = new HashSet<string>(StringComparer.Ordinal);
    
    private void EnsureDefinition(string designKey, IElement carrier)
    {
        if (!_built.Add(designKey))
        {
            return;
        }
    
        var members = new List<DefinitionMember>();
    
        // The design's own geometry is already authored in design space, so it goes in at
        // identity. The placement transform belongs to the occurrence, not to the definition.
        foreach (var geometry in GeometryOf(carrier))
        {
            members.Add(new GeometryMember
            {
                Geometry = _host.ConvertGeometry(geometry),
                Placement = new Matrix4d(),
                SourceElement = null,
            });
        }
    
        // Everything the design contains, each at its own local transform. A child that has
        // content below it becomes a nested definition; a leaf is drawn into this definition.
        foreach (var child in carrier.GetChildElements())
        {
            var childKey = DefinitionKeyOf(child);
            if (childKey != null)
            {
                EnsureDefinition(childKey, child);
                members.Add(new NestedDefinitionMember
                {
                    DesignKey = childKey,
                    Placement = PlacementOf(child),
                    SourceElement = child,
                });
                continue;
            }
    
            foreach (var geometry in GeometryOf(child))
            {
                members.Add(new GeometryMember
                {
                    Geometry = _host.ConvertGeometry(geometry),
                    Placement = PlacementOf(child),
                    SourceElement = child,
                });
            }
        }
    
        _host.CreateDefinition(designKey, DisplayNameOf(carrier), members);
    }
    
    Show More

    Name the definition after the design rather than after the occurrence that carried it, so the three chairs produce one definition called Chair instead of one called Chair 1:

    private static string DisplayNameOf(IElement carrier)
    {
        // Read Design.Name only when the element carries a design reference. Reading it on an
        // element that carries no design throws.
        var designName = carrier.Design?.IsDesignReference == true ? carrier.Design.Name : null;
    
        if (!string.IsNullOrWhiteSpace(designName))
        {
            return designName;
        }
    
        return string.IsNullOrWhiteSpace(carrier.Name) ? "Design" : carrier.Name;
    }
    
    Show More

    Step 5: Turn members into host objects

    A design contains four different things, and they collapse into two host actions:

    In the modelMember the loader emitsHost action
    The design's own geometry GeometryMember, SourceElement is null Draw
    A leaf child element with geometry GeometryMember, SourceElement is the child Draw
    An occurrence of another design NestedDefinitionMember Embed
    A child that has content below it NestedDefinitionMember Embed

    The first two rows differ in origin, not in what your host does: both put geometry into the definition being built. SourceElement preserves the difference so you can attribute the object you create back to an element and stamp its id, name, and parameters onto it. Because it’s null for the design’s own geometry, your attribute builder has to accept null.

    The last two rows are one action from two causes. One design is shared and gets placed many times; the other is used once but still needs to be a definition so the host has something to nest. Neither the loader nor your host distinguishes them.

    Keep three verbs distinct as you implement CreateDefinition:

    VerbCalled fromMeaning
    Draw Inside CreateDefinition Raw geometry becomes part of this definition
    Embed Inside CreateDefinition Another definition becomes part of this one
    Place The loader's outer walk An occurrence appears in the document

    You never place while iterating members. Placing happens once per top-level occurrence, and a nested design inside a definition is embedded instead — the same idea one level down, through a different host API. A nested member’s definition always exists by the time your host sees it, because the loader builds children before the parents that reference them. That ordering relies on design containment being acyclic: no design contains an occurrence of itself, directly or through the designs it nests. The SDK enforces this on the producer side, rejecting an instantiation that would close a cycle, so an exchange written through the SDK gives you that guarantee.

    Every Placement is a single local transform, relative to the definition being built, never composed across levels. Nesting composes them, and a host with native instancing does that for you when you place one definition inside another.

    Identify designs by unique id

    Authoring and loading call for different identifiers, and the asymmetry matters for any connector that consumes exchanges it didn’t write.

    Authoring uses SourceId legitimately. It’s your own key, you chose it, and it’s how you find a design again on the next sync without keeping a side map.

    Loading has no such guarantee. The exchange may have been written by a different connector, so its source ids follow conventions you don’t control, may collide across designs from separate sources, or may be absent — SourceId can be null. UniqueId is system-generated, present whenever a design exists, and persistent, which makes it the right key for the loader’s set of built definitions.

    Geometry arrives in design space

    GetElementGeometriesAsync returns each design’s geometry as it was authored. All three chairs receive identical geometry, the only thing separating them is Transformation, and the SDK never applies it for you.

    For a nested design, the world placement composes as M_world(leg) = M_instance(chair) · M_child(leg). Matrix4d is row-major with the translation in M14, M24, and M34, so points transform as p' = M · p and the parent’s transform applies outermost. If your host has native instancing, don’t compose these by hand: build each definition with its members at their local transforms and let the host compose them as it places one definition inside another.

    Complete example

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading;
    using System.Threading.Tasks;
    using Autodesk.DataExchange.Interface;
    using Autodesk.DataExchange.Models.Math;
    
    public sealed class DesignInstanceLoader
    {
        private readonly IElementDataModel _model;
        private readonly IHostDocument _host;
    
        // The design keys whose definitions already exist in the host. The first occurrence of a
        // design builds the definition; every later one goes straight to placing it. A set is
        // enough, because the host keeps its own key to native handle map. Store the ids rather
        // than the design objects: each traversal creates new wrapper objects.
        private readonly HashSet<string> _built = new HashSet<string>(StringComparer.Ordinal);
    
        // Element unique id to its downloaded geometry.
        private Dictionary<string, IReadOnlyList<IElementGeometry>> _geometry;
    
        public DesignInstanceLoader(IElementDataModel model, IHostDocument host)
        {
            _model = model;
            _host = host;
        }
    
        public async Task LoadAsync(CancellationToken cancellationToken)
        {
            await DownloadGeometryAsync(cancellationToken).ConfigureAwait(false);
    
            // Only the root's direct children are placed. Anything nested inside a design is
            // realized when that design's definition is built.
            foreach (var element in _model.TopLevelElements)
            {
                Place(element);
            }
        }
    
        private void Place(IElement element)
        {
            var key = DefinitionKeyOf(element);
    
            if (key != null)
            {
                EnsureDefinition(key, element);
                _host.PlaceInstance(key, PlacementOf(element), element.Name);
                return;
            }
    
            foreach (var geometry in GeometryOf(element))
            {
                _host.DrawGeometry(_host.ConvertGeometry(geometry), PlacementOf(element), element.Name);
            }
        }
    
        private void EnsureDefinition(string designKey, IElement carrier)
        {
            if (!_built.Add(designKey))
            {
                return;
            }
    
            var members = new List<DefinitionMember>();
    
            foreach (var geometry in GeometryOf(carrier))
            {
                members.Add(new GeometryMember
                {
                    Geometry = _host.ConvertGeometry(geometry),
                    Placement = new Matrix4d(),
                    SourceElement = null,
                });
            }
    
            foreach (var child in carrier.GetChildElements())
            {
                var childKey = DefinitionKeyOf(child);
                if (childKey != null)
                {
                    EnsureDefinition(childKey, child);
                    members.Add(new NestedDefinitionMember
                    {
                        DesignKey = childKey,
                        Placement = PlacementOf(child),
                        SourceElement = child,
                    });
                    continue;
                }
    
                foreach (var geometry in GeometryOf(child))
                {
                    members.Add(new GeometryMember
                    {
                        Geometry = _host.ConvertGeometry(geometry),
                        Placement = PlacementOf(child),
                        SourceElement = child,
                    });
                }
            }
    
            _host.CreateDefinition(designKey, DisplayNameOf(carrier), members);
        }
    
        private static string DefinitionKeyOf(IElement element)
        {
            if (element.Design?.IsDesignReference == true)
            {
                return element.Design.UniqueId;
            }
    
            if (element.GetChildElements().Any())
            {
                return element.UniqueId;
            }
    
            return null;
        }
    
        private static string DisplayNameOf(IElement carrier)
        {
            var designName = carrier.Design?.IsDesignReference == true ? carrier.Design.Name : null;
    
            if (!string.IsNullOrWhiteSpace(designName))
            {
                return designName;
            }
    
            return string.IsNullOrWhiteSpace(carrier.Name) ? "Design" : carrier.Name;
        }
    
        private static Matrix4d PlacementOf(IElement element)
            => element.Transformation?.Matrix ?? new Matrix4d();
    
        private IReadOnlyList<IElementGeometry> GeometryOf(IElement element)
            => _geometry.TryGetValue(element.UniqueId, out var geometry)
                ? geometry
                : Array.Empty<IElementGeometry>();
    
        private async Task DownloadGeometryAsync(CancellationToken cancellationToken)
        {
            var downloaded = await _model
                .GetElementGeometriesAsync(_model.Elements, cancellationToken)
                .ConfigureAwait(false);
    
            _geometry = new Dictionary<string, IReadOnlyList<IElementGeometry>>(StringComparer.Ordinal);
    
            foreach (var pair in downloaded)
            {
                if (pair.Value != null)
                {
                    _geometry[pair.Key.UniqueId] = pair.Value.ToList();
                }
            }
        }
    }
    
    Show More

    Verify the result

    Run the loader against the chair exchange and follow what it does:

    CallResult
    Place(chair-001) The Chair design isn't built yet, so build it
    Build Chair Seat geometry at identity, plus four leg children that are design references
    Build Leg Not built yet, so create the leg definition: one geometry, no children
    Legs 2 to 4 Already built, so four nested references at (0,0,0), (0.4,0,0), (0,0.4,0), and (0.4,0.4,0)
    Place chair-001 Create the Chair definition with five members, then place it at (0,0,0)
    Place(chair-002) Already built, so place at (1.5,0,0)
    Place(chair-003) Already built, so place at (3.0,0,0)

    A correct load produces two definitions, three placements, and two geometry downloads. The host document then holds one Chair definition containing a seat and four nested Leg references, one Leg definition, three chair occurrences 1.5 units apart, and twelve visible legs backed by a single leg geometry.

    Troubleshoot common problems

    SymptomCauseFix
    Legs are drawn once per chair, so twelve exist instead of four The walk descends into a definition's children after placing the definition Place top-level elements only, and let each definition own its subtree
    Four extra legs appear at unexpected positions Placement is driven from the flattened Elements list Drive placement from TopLevelElements
    Nested elements load with no geometry TopLevelElements was passed to the geometry download, which doesn't descend into children Pass the flattened Elements list to GetElementGeometriesAsync
    A geometry lookup finds nothing for an element that has geometry A dictionary is keyed by an element wrapper instead of by unique id Re-key the returned dictionary by UniqueId
    Every occurrence lands at the origin The instance transform was never applied; geometry arrives in design space Apply element.Transformation.Matrix when you place
    NullReferenceException reading Design.Name or Design.SourceId The element carries no design, and Design is non-null regardless Test IsDesignReference == true before reading any other member
    The host rejects a definition name as a duplicate Display names aren't unique across designs Disambiguate with the design key in your host layer
    ArgumentException while building the geometry map ToDictionary hit a repeated unique id Assign through the dictionary indexer instead

    See also