Pattern/Strategy for creating BOs from DTOs
I like the approach of having property bag objects (DTOs) which define the interface to my server, but I don't like writing code like this:
void ModifyDataSomeWay(WibbleDTO wibbleDTO)
{
WibbleBOWithMethods wibbleBO = new WibbleBOWithMethods();
wi开发者_开发知识库bbleBO.Val1 = wibbleDTO.Val1;
wibbleBO.Val2 = wibbleDTO.Val2;
}
This copying code is quite laborious to write. If the copying code is unavoidable, then where do you put it? In the BO? In a factory? If it is possible to manually avoid writing the boiler plate code then how?
Thanks in advance.
That looks like a job for AutoMapper, or (simpler) just add some interfaces.
This needs more error handling, and you may need to modify it accommodate properties where the data types don't match, but this shows the essence of a simple solution.
public void CopyTo(object source, object destination)
{
var sourceProperties = source.GetType().GetProperties()
.Where(p => p.CanRead);
var destinationProperties = destination.GetType()
.GetProperties().Where(p => p.CanWrite);
foreach (var property in sourceProperties)
{
var targets = (from d in destinationProperties
where d.Name == property.Name
select d).ToList();
if (targets.Count == 0)
continue;
var activeProperty = targets[0];
object value = property.GetValue(source, null);
activeProperty.SetValue(destination, value, null);
}
}
Automapper (or similar tools) might be the way forward here. Another approach may be the factory pattern.
Simplest of all would be something like this:
class WibbleBO
{
public static WibbleBO FromData(WibbleDTO data)
{
return new WibbleBO
{
Val1 = data.Val1,
Val2 = data.Val2,
Val3 = ... // and so on..
};
}
}
精彩评论