所以我有一個接口,用於DI:AutoMapper嵌套映射
public interface IMapper<in TIn, out TOut>
{
TOut Map(TIn objectToMap);
}
和基類爲我的映射器:
public abstract class MapperBase<TIn, TOut> : IMapper<TIn, TOut>
{
internal IConfigurationProvider MapperConfiguration { get; set; }
public TOut Map(TIn objectToMap)
{
return MapperConfiguration.CreateMapper().Map<TOut>(objectToMap);
}
}
我會使用下列簡化數據模型(」相同的」用於DAL和服務層)
public class Client
{
public int Id { get; set; }
public List<Contract> Contracts { get; set; }
}
public class Contract
{
public int Id { get; set; }
public List<Installation> Installations { get; set; }
}
public class Installation
{
public int Id { get; set; }
}
我有DAL和服務層之間的以下映射器:
public class DalClientToServiceMapper : MapperBase<DAL.Client, Interface.Model.Client>
{
public DalClientToServiceMapper(IMapper<DAL.Contract, Interface.Model.Contract> contractMapper)
{
MapperConfiguration = new MapperConfiguration(cfg =>
{
cfg.CreateMap<DAL.Client, Interface.Model.Client>();
cfg.CreateMap<DAL.Contract, Interface.Model.Contract>().ConstructUsing(contractMapper.Map);
});
}
}
public class DalContractToServiceMapper : MapperBase<DAL.Contract, Interface.Model.Contract>
{
public DalContractToServiceMapper(IMapper<DAL.Installation, Interface.Model.Installation> dalInstallationToServiceMapper)
{
MapperConfiguration = new MapperConfiguration(cfg =>
{
cfg.CreateMap<DAL.Contract, Interface.Model.Contract>();
cfg.CreateMap<DAL.Installation, Interface.Model.Installation>().ConstructUsing(dalInstallationToServiceMapper.Map);
});
}
}
public class DalInstallationToServiceMapper : MapperBase<DAL.Installation, Interface.Model.Installation>
{
public DalInstallationToServiceMapper()
{
MapperConfiguration = new MapperConfiguration(cfg =>
{
cfg.CreateMap<DAL.Installation, Interface.Model.Installation>();
});
}
}
但當我映射一個客戶端,AutoMapper給了我一個異常說,有用於安裝沒有定義的映射(嵌套嵌套型)。
當我在Client Mapper中配置安裝映射時,它工作正常。
我不明白的是,我提供了一個特定的方法來映射來自「客戶端」的嵌套類型「Contract」,以及特定映射來自「Contract」的「Installation」,那麼爲什麼automapper試圖使用他的嵌套類型的嵌套類型的映射配置?他爲什麼不在那裏停下來,並使用我提供的方法?我怎樣才能在這裏實現我想要做的,鏈接映射器?