using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using zero.Core.Entities;
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 IEnumerable Map(IEnumerable source) where TTarget : class, new()
{
IList target = new List();
foreach (TSource item in source)
{
target.Add(Map(item, new TTarget()));
}
return target;
}
///
public ListResult Map(ListResult source) where TTarget : class, new()
{
IList target = new List();
foreach (TSource item in source.Items)
{
target.Add(Map(item, new TTarget()));
}
return new ListResult(target, source.TotalItems, source.Page, source.PageSize)
{
Statistics = source.Statistics
};
}
///
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