using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace zero.Web.Mapper
{
public class DefaultMapper : IMapper
{
MapCache Maps = new MapCache();
///
public void Add() where T : IMapperConfig, new()
{
T config = new T();
config.Configure(this);
}
///
public void Add(Assembly assembly)
{
Type configType = typeof(IMapperConfig);
IEnumerable types = assembly.GetTypes().Where(t => t.IsAssignableFrom(configType));
foreach (Type type in types)
{
IMapperConfig config = (IMapperConfig)Activator.CreateInstance(type);
config.Configure(this);
}
}
///
public TTarget Map(TSource source) where TTarget : class, new()
{
if (source == null)
{
return null;
}
return Map(source, new TTarget());
}
///
public TTarget Map(TSource source, TTarget target) where TTarget : class, new()
{
if (source == null)
{
return target;
}
Maps.Call(source, target);
return target;
}
///
public void CreateMap(Action map) where TTarget : class, new()
{
Maps.Add((source, target) => map((TSource)source, (TTarget)target));
}
///
/// Internal mappings cache
///
class MapCache : Dictionary>>
{
int Index = 0;
Dictionary TypeMappings = new Dictionary();
///
/// Adds a new action for the mapping
///
public void Add(Action