You are here: Platform Specific Issues > Disconnected Objects > Comparison Of Different IDs > Example ID-Generator

Example ID-Generator

This example demonstrates how you can use an ID-generator to identify objects across objects containers. Take a look advantages and disadvantages of ID-generators: See "Comparison Of Different IDs"

This example assumes that all object have a common super-class, IDHolder, which holds the id.

private int id;

public int Id
{
    get { return id; }
    set { id = value; }
}
IDHolder.cs: id holder
Private m_id As Integer

Public Property Id() As Integer
    Get
        Return m_id
    End Get
    Set(ByVal value As Integer)
        m_id = value
    End Set
End Property
IDHolder.vb: id holder

Don't forget to index the id-field. Otherwise finding objects by id will be slow.

configuration.Common.ObjectClass(typeof (IDHolder)).ObjectField("id").Indexed(true);
AutoIncrementExample.cs: index the id-field
configuration.Common.ObjectClass(GetType(IDHolder)).ObjectField("id").Indexed(True)
AutoIncrementExample.vb: index the id-field

The hard part is to write an efficient ID-Generator. For this example a very simple auto increment generator is used. Use the creating-callback-event in order to add the ids to the object. When committing, store the state of the id-generator.

AutoIncrement increment = new AutoIncrement(container);
IEventRegistry eventRegistry = EventRegistryFactory.ForObjectContainer(container);

eventRegistry.Creating+=
    delegate(object sender, CancellableObjectEventArgs args)
    {
        if (args.Object is IDHolder)
        {
            IDHolder idHolder = (IDHolder)args.Object;
            idHolder.Id = increment.GetNextID(idHolder.GetType());
        }    
    };
eventRegistry.Committing +=
    delegate(object sender, CommitEventArgs args)
        {
            increment.StoreState();    
        };
AutoIncrementExample.cs: use events to assign the ids
Dim increment As New AutoIncrement(container)
Dim eventRegistry As IEventRegistry = EventRegistryFactory.ForObjectContainer(container)

AddHandler eventRegistry.Creating, AddressOf increment.HandleCreating
AddHandler eventRegistry.Committing, AddressOf increment.HandleCommiting
AutoIncrementExample.vb: use events to assign the ids

The id is hold by the object itself, so you can get it directly.

IDHolder idHolder = (IDHolder) obj;
int id = idHolder.Id;
AutoIncrementExample.cs: get the id
Dim idHolder As IDHolder = DirectCast(obj, IDHolder)
Dim id As Integer = idHolder.Id
AutoIncrementExample.vb: get the id

You can get the object you can by a regular query.

object instance = container.Query(delegate(IDHolder o) { return o.Id == id; })[0];
AutoIncrementExample.cs: get an object by its id
Dim instance As Object = container.Query(Function(o As IDHolder) o.Id = id)(0)
AutoIncrementExample.vb: get an object by its id