There are two distinct ways to map: Automagical or Strict. In automagical mode Glue tries to instantiate objects whenever necessary. In Strict mode Glue does not create any objects (making you create all the objects). Choosing between the modes is simply done by choosing the right overload of the Mapper.Map-method. Intellisense will guide you. Here are some examples:

Given we want to map between the types DomainPerson and GuiPerson:

public class DomainPerson
{
    public String Name { get; set; }
    public DomainAddress Address { get; set; }
}

public class DomainAddress
{
    public String StreetAddress { get; set; }
}

public class GuiPerson
{
    public String Name { get; set; }
    public GuiAddress Address { get; set; }
}

public class GuiAddress
{
    public String StreetAddress { get; set; }
}
And you create this DomainPerson:

domainPerson = new DomainPerson
{
    Name = "Tore",
    Address = new DomainAddress { StreetAddress = "the street address" }
};

Automagical Mode

In automagical mode, you can just map like this, and Glue creates the GuiPerson-object for you:

var guiPerson =mapping.Map(domainPerson);
Assert.Equal(domainPerson.Name,guiPerson.Name);
Assert.Equal(domainPerson.Address.StreetAddress, guiPerson.Address.StreetAddress);
Note that in this case both a GuiPerson and a GuiAddress object is created by Glue. This works great as long as the classes have parameterless constructors.

If you, on the other hand, have a class with a constructor (with parameters), Glue does not know by default how to instantiate it. In automagical mode, you can get by this with specifying a Creator. This is how you specify a Creator:

complexMapping.AddCreator(typeof(GuiPersonWithConstructor), x => new GuiPersonWithConstructor(""));
var guiPerson = complexMapping.Map(domainPerson);
Assert.Equal(domainPerson.Name, guiPerson.Name);
Assert.Equal(domainPerson.Address.StreetAddress, guiPerson.Address.StreetAddress);

Strict Mode

In strict mode, Glue will not create any objects for you. To use Strict mode, you just use the other mapper.Map method:

var guiPerson = new GuiPerson {Address = new GuiAddress()};
mapping.Map(domainPerson, guiPerson);
Assert.Equal(domainPerson.Name, guiPerson.Name);
Assert.Equal(domainPerson.Address.StreetAddress, guiPerson.Address.StreetAddress);
Here you pass both the from object and to object (domainPerson and guiPerson) to Glue (since it will not create GuiPerson for you). It is also important to notice that you also have to instantiate all nested objects. In this case guiPersons Address-property must be instantiated (a GuiAddress object). If this is not done, the mapping will fail:

var guiPerson = new GuiPerson {Address = null};
Assert.Throws(typeof(GlueException), ()=> mapping.Map(domainPerson, guiPerson));

You can read more about why there are two modes here.

Last edited Jan 6, 2011 at 10:23 AM by ToreVestues, version 5

Comments

No comments yet.